In this article, we will learn about the uncaught error “Uncaught error: Call to undefined function mysql_connect()”.
This error is encountered when we try to use “mysql_connect()” functions of php5 in php7.
PHP Fatal error: Uncaught Error: Call to undefined function mysql_connect() error is raised because mysql_* functions are completely removed from PHP 7, it previously got deprecated in PHP 5.5, but now it is completely removed.
The older MySQL function are removed due to the following reasons:
- Do not work on Object-Oriented concept
- Won’t support transactions and prepared statements
How to fix Undefined Function Mysql_connect() error
There are four methods to fix undefined function Mysql_connect() error:
- Use MySQLi or PDO
- Connecting to Mysql with the Pdo Object Is Pretty Straight Forward
- Connecting to MySQL with MySqli Connection Object
- Rollback to Older PHP 5, update your code to mysqli or PDO and then upgrade to PHP7
1. Use MySQLi or PDO
Instead of using “mysql_connect()” we should use “mysqli_connect()” in php7 to avoid this error.
Example: $mysql = new mysqli(“localhost”,”root”,”password”,”DB_name”);
PDO(php database objects):
Example:$pdo = new PDO(‘mysql:host=localhost;dbname=database_name ‘, ‘username’, ‘password’);
//pdo requires a valid database to establish connection. If the database is not specified then it throws an exception.
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.