Skip to content

You say mysql — I say mysqli

We’re finishing up a big PITA migration here at The Job and maybe this will help you, dear reader, if you ever have to deal with a tangle like this.

We’ve got dozens of individual projects on a server, some of which date back to PHP 4.something. Along the way it was upgraded to PHP 5. All along the way as I was teaching myself PHP (I entered The Job as a Perl guy!) and MySQL (we did MSSQL at The Previous Job). So naturally my coding standards — ahem — evolved over the years.

But if it ain’t broke don’t fix it, right? Oftentimes they just got abandoned anyway. So the older projects kept humming along in their outmoded less-efficient ways.

Well enter PHP7 and a whole new way of doing business. Under PHP5 the old mysql() commands at least worked. Now they’re history. Rather than go through a few thousand files one by one, I just cooked up a set of commands that I could paste into the shell one by one and run them. For your edification and amusement, here they are.

Assume you use $link for your MySQLI object. If you use something else, $mysqli or the like, change these accordingly.


find . -type f -name "*.php" | xargs sed -i 's|mysql_fetch_array|mysqli_fetch_array|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_fetch_assoc|mysqli_fetch_assoc|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_fetch_row|mysqli_fetch_row|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_num_rows|mysqli_num_rows|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_num_fields|mysqli_num_fields|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_fetch_field|mysqli_fetch_field|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_close|mysqli_close|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_error[(]|mysqli_error(\$link|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_query[(]|mysqli_query($link,|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_unbuffered_query[(]|mysqli_query($link,|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_real_escape_string[(]|mysqli_real_escape_string(\$link,|g'
find . -type f -name "*.php" | xargs sed -i 's|mysql_insert_id[(]|mysqli_insert_id($link,|g'

If you’re still finding errors, try to


grep -Rl mysql_

Then try to untangle what the new command is. It’s not always straightforward, and it’s not always possible.

p.s. In case you’re wondering why in these modern times I was still using PHP5, well we get upgrades when we get upgrades.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Share This