uncaught error: Call to undefined function mysql_connect()
After upgrading to PHP 7 from PHP 5, I start getting an error
PHP Fatal error: Uncaught Error: Call to undefined function mysql_connect()
This is because mysql_* functions are completely removed from PHP 7, it got deprecated in PHP 5.5, but now it is completely removed.
The older mysql function are removed due to the following reasons:
- Not work on Object-Oriented concept
- Won't support transactions and prepared statements
How to fix Undefined Function Mysql_connect() error
1. Use MySQLi or PDO
2. Connecting to MySQL with the PDO object is pretty straight forward:
$user = 'root'; // Mysql User $password = ''; // Mysql Password $server = 'localhost'; // Mysql Host $database = 'my_database'; // Mysql Databse // PDO Connection string $pdo = new PDO("mysql:host=$server;dbname=$database", $user, $password);
3 Connecting to MySQL with MySqli connection object
$con = mysqli_connect('localhost', 'username', 'password', 'database');
4. Rollback to Older PHP 5, update your code to mysqli or PDO and then upgrade to PHP7
Use MySQLi wrapper and object mapper with prepared statements.
Example: User PHP-MySQLi-Database-Class https://github.com/ThingEngineer/PHP-MySQLi-Database-Class
By using MySQLi with prepare statement will secure your database connection & in future, if need to upgrade your Database to some other version, you won't have to update all you mysql connection string in all pages.
This package is free and customizable; you can upgrade by creating your Class & functions.