php

PHP MySQL Connect

The PHP MySQL connect function allows you to create a non-persistent connection to the MySQL database. It takes the hostname, username, password, and target database as parameters and connects to the server.

The function’s syntax is as shown:

mysql_connect(string $server, string $username, string $password);

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.

<?PHP
    $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.

<?PHP
    $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.

<?PHP
    $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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list