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.
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.
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";
?>
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();
}
?>
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
For more detailed guidance, check out these resources: