Why am I getting Fatal error: Uncaught Error: Call to undefined function mysql_connect() in my PHP script?

Understanding and Resolving the mysql_connect() Error in PHP

If you encounter the error Fatal error: Uncaught Error: Call to undefined function mysql_connect() in your PHP script, it is likely due to using a deprecated function. Here are the steps to resolve this issue.

1. Deprecated mysql_connect() Function

Cause: The mysql_connect() function was deprecated in PHP 5.5.0 and removed in PHP 7.0.0. It is no longer available in modern versions of PHP.

Fix: Use the MySQLi or PDO_MySQL extension instead. These extensions provide improved functionality and security.

2. Using MySQLi Extension

To replace mysql_connect() with MySQLi, you can use the following code:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

3. Using PDO_MySQL Extension

Alternatively, you can use PDO for database connections. Here is an example:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
}
catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

4. Installing MySQLi Extension

If you decide to use MySQLi and it is not already installed, you can install it using the following command:

sudo apt-get install php-mysqli

After installing the extension, restart your web server:

sudo service apache2 restart

5. Additional Resources

For more detailed guidance, check out these resources: