The function’s syntax is as shown:
It returns a Boolean true on success and Boolean false on fail. You can then use the return values to perform actions using if…else statements.
Example 1
The following example shows you how to use the mysql_connect function to establish a primary connection to the MySQL database.
$conn = mysql_connect("localhost", "mysql_user", "mysql_pass");
if (!$conn) {
die("Connection failed...[Error!]");
}
else {
echo "Connection successful...[OK]", "\n";
}
mysql_close($conn);
?>
Example 2
The example below uses hostname:port to connect to a MySQL server.
$conn = mysql_connect("127.0.0.1:9999", "mysql_user", "mysql_pass");
if (!$conn) {
die("Connection failed...[Error!]");
}
else {
echo "Connection successful...[OK]", "\n";
}
mysql_close($conn);
?>
Example 3
You can also use socket connection as shown in the example below.
$conn = mysql_connect("localhost:/net/socks/mysql.sock", "mysql_user", "mysql_pass");
if (!$conn) {
die("Connection failed...[Error!]" . mysql_error());
}
else {
echo "Connection successful...[OK]", "\n";
}
mysql_close($conn);
?>
MySQLi or PDO
In recent versions of PHP, you will notice the MySQL extension is deprecated and no longer supported.
To use MySQL and PHP with no errors, use the MySQLi extension or PHP Data Objects.
We can not go over the details and how either PDO or MySQLi works. However, MySQLi will only work with the MySQL database. On the other hand, PDO will work on different database systems, which can be beneficial if you need to switch.
By default, the PHP MySQLi extension is installed and enabled on most systems. You can learn how to install PDO extension in the resource provided below:
https://www.php.net/manual/en/pdo.installation.php
Closing
This short guide gives a walkthrough of using the mysql_connect function to create connections to the database.
Thanks for reading.