Midnight Engineer Midnight Engineer - 4 years ago 189
PHP Question

Can I blindly replace all mysql_ functions with mysqli_?

I have used

throughout my project; but I've just learned that
was deprecated as of PHP 5.5, has been removed in PHP 7.

So, I would like to know if I can replace all
functions with
in my project blindly? For example, just replacing
. Is there any adverse effect?

Answer Source

The short answer is no, the functions are not equivalent.

The good news is there is a converter tool that will help you if you've got a lot of calls/projects to change. This will allow your scripts to work right away.


It's a forked version of the Oracle version, so it's kosher.

That said, it's not too difficult to update your code, and you might want to migrate to an object orientated methodology anyway ...

1) The Connection

For all intents and purposes, you need a new connection function that saves the connection as a PHP variable, for example;

$mysqli = new mysqli($host,$username,$password,$database);

Notice I've saved the connection to $mysqli. You can save to $db or whatever you like, but you should use this throughout your code to reference the connection.

Remember to check for a connection error though;

if ($mysqli->connect_errno) echo "Error - Failed to connect to MySQL: " . $mysqli->connect_error;

2) The Query

Note: You should protect against SQL injection. Take a look at How can I prevent SQL-injection in PHP?, but I'm just going to cover the basics here.

You now have to include the connection as an argument in your query, and other mysqli_ functions. In procedural code it's the first argument, in OO you write it like a class method;


$result = mysqli_query($mysqli,$sql);


$result = $mysqli->query($sql);

3) Fetch Result

The fetching of the result is similar to the old mysql_ function in procedural;

while($row = mysqli_fetch_assoc($result))

but as $result is now an object in mysqli, you can use the object function call;

while($row = $result->fetch_assoc())

4) Close Connection

So as before, you need to include the connection in the close function; as an argument in procedural;


and as the object that you run the function on in OO;


I would be here forever if I went through them all, but you get the idea. Take a look at the documentation for more information. Don't forget to convert any connection close, result release, or error and row counting functions you have.

The basic rule of thumb is for functions that use the database connection, you need to include it in the function now (either as the first argument in procedural, or the object you use to call the function in OO), or for a result set you can just change the function to mysqli_ or use the result set as the object.

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download