How to fix the mysql problems after upgrading php 5 to php 7?

If you ever upgrade php5 to php7 for your server/vps/shared hosting, you probably encounter the following errors:

  • Fatal error: Uncaught Error: Call to undefined function mysql_connect()
  • Fatal error: Uncaught Error: Call to undefined function mysql_select_db()
  • Fatal error: Uncaught Error: Call to undefined function mysql_query()
  • Fatal error: Uncaught Error: Call to undefined function mysql_fetch_array()
  • Fatal error: Uncaught Error: Call to undefined function mysql_close()

The reason is the mysql functions mysql_xxx that are working on php 5 are deprecated now and removed from php 7.  Fixing these errors is not difficult.

First, you should replace all mysql_xxx with mysqli_xxx, e.g, mysql_connect is replaced by mysqli_connect, mysql_select_db is replaced by mysqli_select_db, mysql_query is replaced by mysqli_query, mysql_fetch_array is replaced by mysqli_fetch_array, mysql_close is replaced by mysqli_close.

But simply changing the function names is not enough. You’ll get the following errors:

  • Warning: mysqli_select_db() expects exactly 2 parameters, 1 given
  • Warning: mysqli_query() expects at least 2 parameters, 1 given
  • Warning: mysqli_query() expects at least 2 parameters, 1 given
  • Warning: mysqli_query() expects at least 2 parameters, 1 given

This is because there is no such concept as current connection or default connection for mysqli_xxx as in mysql_xxx.  You should provide the connection you create with mysqli_connect as the first parameter of mysqli_xxx, e.g., mysqli_query($con,”…”).  Note that the deprecated mysql_select_db() can also take the connection parameter, but as the second parameter, not the first one.

Note also that the mysqli_xxx function also exist in php 5.6 so the modified code works on php 5 as well.

Posted in

Leave a Reply