Online Tutorials & Training Materials | STechies.com
Register Login

Fatal Error: Uncaught error: Call to undefined function mysql_connect()

30 Dec 2018 11:38 am || 0

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:

  1. Not work on Object-Oriented concept
  2. Won't support  transactions and prepared statements
  3. Insecure

How to fix Undefined Function Mysql_connect() error

1. Use MySQLi or PDO

mysqli_connect()
PDO::__construct()

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

Best Practice

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.