Which is fastest in PHP- MySQL or MySQLi? - php

I'd like to know if anyone has any first-hand experience with this dichotomy. A few blogs say the mysql extension is faster than mysqli. Is this true?
And I'm only asking about speed. I know mysqli has features that are not present in the older extension.

The MySQL extension is very slightly faster than MySQLi in most benchmarks I've seen reported. The difference is so slight, however, that this should probably not be your criterion for deciding between the two.
Other factors dwarf the difference in performance between mysql and mysqli. Using mod_php or FastCGI, a bytecode cache like APC, or using data caching judiciously to reduce database hits, are far more beneficial for overall performance of PHP scripts than the choice of MySQL extension.
Don't be penny wise and pound foolish! :-)

"It depends."
For example, PHP MySQL vs MySQLi Database Access Metrics and the subsequent comments point out arguments both ways.
If you have a mature database and codebase, do some testing and see what works in your system. If not, stop worrying about premature optimization.

See http://php.net/manual/en/mysqlinfo.api.choosing.php
The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

According to all the Google results for benchmarks linked by ceejayoz it looks like MySQL is at least slightly faster than MySQLi in all the benchmark tests. I do recommend reading the results for details but just figured I'd post something that directly answered the question and bumps up ceejayoz's answer.

The PHP documentation has a good comparison of mysql, mysqli, and PDO. I know you only asked about speed, but others might find this useful. It talks about the feature differences between the options.

Maybe, this can be a reason to make the right choice :: The Plot to
Kill PHP MySQL Extension
" Yes, you read it right. Recently, Phillip Olson sent to the PHP internals mailing list a proposal to kill the original PHP MySQL extension in future PHP versions. "

In relation to PHP programming language, MySQL is the old database driver, and MySQLi is the Improved driver. MySQLi takes advantage of the newer features of MySQL 5.
Features of MySQLi taken from php.net site:
Object-oriented interface
Support for Prepared Statements
Support for Multiple Statements
Support for Transactions
Enhanced debugging capabilities
Embedded server support

Unless milliseconds matter then don't worry. Surely if you have no need for the extra functionality provided by mysqli then just stick with the tried and tested mysql.

<?php
$start = microtime();
$c = new mysqli('localhost', 'username', 'userpass', 'username_dbname');
$c -> select_db('username_dbname');
$q = $c -> query("SELECT * FROM example");
while ($r = $q -> fetch_array(MYSQLI_ASSOC))
{
echo $r['col1'] . "<br/>\n";
}
$me = $c -> query("SELECT col1 FROM example WHERE id='11'") -> fetch_array(MYSQLI_ASSOC);
echo $me['col1'];
echo (microtime() - $start);
?>
Why when using mysqli oop is there a slight speed increase from using this script with mysql or mysqli procedural style? When testing the above script I get .0009 seconds consistantly more than when using the other 2. When using mysql or mysqli procedural, I loaded the scripts 20x in each different style and the two were always above .001. I load the above script 20x and I get below .001 5x.

MySQLi has two basic advantages over MySQL; prepared statements are a great way to avoid SQL injection attacks. Secondly MySQL (or mariaDB) will do their best to optimize prepared statements and thus you have the potential for speed optimizations there. Speed increases from making the database happy will vastly outsize the tiny difference between MySQL and MySQLi.
If you are feeding in statements you mangle together yourself like SELECT * FROM users WHERE ID=$user_id the database will treat this as a unique statement with each new value of $user_id. But a prepared statement SELECT * FROM users WHERE ID=? stands a much better chance of having some optimizations/caching performed by the database.
But comparisons are fairly moot as MySQL is now officially deprecated. From the horse's mouth:
Deprecated features in PHP 5.5.x
ext/mysql deprecation
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.

Related

Detect what part of MySQL queries works via mysql and mysqli

Can I somehow detect how much MySQL queries performed via old mysql and how much via mysqli connections.
My basic work is recode, refactor and support old projects. I migrate from procedural to OOP style and from mysql to mysqli. I need to know how much old requests left from old coders (code is messy and crazy as usual to calculate this in code directly).
Thanks!
mysqli has http://php.net/manual/en/mysqli.get-connection-stats.php
and for any driver you can run show status like 'Com\_%'; query.
I see no point in such numbers though, for the task provided.
You can override both methods with override_function and log whatever you need.

CodeIgniter switching driver from mysql --> mysqli

I was reading this question:
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
And it got me thinking that I should make the change from mysql to mysqli. It is a one character change in CodeIgniter so it isn't very hard :)
But is there anything I should look out for to spot any errors that can happen? Are there certain queries that are treated differently?
Are there certain queries that are treated differently?
No.
The MySQL and MySQLi extension are “drivers” that take care of the communication between PHP and the MySQL database server;
they do not change the range of SQL commands that the MySQL server understands.
So as long as the DB abstraction layer takes care of what PHP functions are to use for what purpose for you (and a framework like CI should most certainly do that), there is nothing to worry about in regard to the actual queries.

mysqli vs mysql-performance and usage of mysqli is complicated

Up until recently I was using mysql instead of mysqli or POD but as PHP has announded that it will not support mysql so i have decided to move to mysqli. But I have read several blogs/article everyone says that for security purpose mysqli is better than mysql but performance wise mysql is better. If you are planning for high traffic website, then this small difference in performance may cause problem. Apart from this performance issue I have found that mysqli and PDO is little complicated to use. For example for select function we can directly use this in my sql:
$res = mysql_query("SELECT * FROM `summary` WHERE id='35' limit 1");
$row = mysql_fetch_array($res);
But in mysqli we have to use this something very complicated query for select/update/delete/insert etc. Is there any way i can use almost similar code for mysqli as well?
If you are planning for high traffic website, then this small
difference in performance may cause problem.
Have you actually tested this out with your code? In many cases it is a negligible difference at best. So I would not worry. Typically these dire warnings of speed differences mean that something that took 1.5 seconds to complete would now take 1.6 seconds.
Besides, PDO adapters are simply the future. That is why they allow for prepared statements via ORM (object-relational mapping) or straight queries (see the example below).
But in mysqli we have to use this something very complicated query for
select/update/delete/insert etc. Is there any way I can use almost
similar code for mysqli as well?
Yes, you can. mysqli has the capabilities to allow you to use pure MySQL queries without using PDO structure:
$db = new mysqli('localhost', 'user', 'pass', 'demo');
$result = $db->query("SELECT * FROM `summary` WHERE id='35' limit 1");
while($row = $result->fetch_assoc()){
echo '<pre>';
print_r($row);
echo '</pre>';
}
Also, if you are truly worried about MySQL performance, then just run a script like this MySQL Tuning Primer script regularly to performance tune your MySQL install. That will do more to improve performance than obsessing over mysql versus mysqli in PHP.

MySQLi Bulk Prepared statements on large site?

I have been digging around stack and all sorts of other sites looking for the best answer to my questions.
I am developing a very large and growing monster of a website, in the form of an information management system. At the core it is running off of PHP and MySQL. I have just updated code, in the more general sense, to mysqli, but without taking full advantage of all of the features. That is part of what I am working on now.
I have read a ton about prepared statements and this is something I certainly need to put to use given the number of statements that get re-used.
I am looking at making in the realm of about 50 prepared statements,
being used across nearly 200 different pages. Is there a recommended
way to do this? All examples I have seen deal with 1 or 2.
Due to the ever growing nature of the site, using databases and such,
one of the things that I liked with the previous mysql is that it
didn't require a connection specified for each query, but does with
mysqli. I had to tweak my functions due to this. Is there a
recommended solution for this?
I built the site in a procedural form rather that object oriented, but I am always open to suggestions, regardless of the format they use.
I'll try to be as accurate as possible, but I'm not an expert.
Your first point: You're probably looking for Stored Procedures. Basically you can store certain logic of your application for repetitive usage.
Prepared Statements, however, are different. They basically mean "Parse once, execute many times" but they're not stored on the server and carried out across connections.
In PHP, each "page load" is a different thread with its own variables and thus its connections to the database, so you cannot really use the Prepared Statement again.
As for your second point, mysql_query() doesn't require a connection handle to be passed to it simply because it assumes you want to use the last created connection.
For example:
mysql_connect();
mysql_query("SELECT * FROM table");
and
$link = mysql_connect();
mysql_query("SELECT * FROM table", $link);
are the same.
So using the connection implicitly doesn't mean scalability.
That's as far as I can write without providing possibly wrong information, so I highly recommend to you really read about this, and then if you have some question everybody here would be happy to answer.

Is the PDO Library faster than the native MySQL Functions?

I have read several questions regarding this but I fear they may be out of date as newer versions of the PDO libraries have been released since these questions were answered.
I have written a MySQL class that builds queries and escapes parameters, and then returns results based on the query. Currently this class is using the built-in mysql functions.
I am well aware of the advantages of using the PDO Library, e.g. it is compatible with other databases, stored procedures are easier to execute etc... However, what I would like to know is simply; is using the PDO Library faster then using the mysql built-in functions?
I have just written the equivalent class for MsSQL, so rewriting it to work with all databases would not take me long at all. Is it worth it or is the PDO library slower?
I found PDO in many situation/projects to be even faster than the more native modules.
Mainly because many patterns/building blocks in a "PDO-application" require less php script driven code and more code is executed in the compiled extension and there is a speed penalty when doing things in the script. Simple, synthetic tests without data and error handling often do not cover this part, which is why (amongst other problems like e.g. measuring inaccuracies) I think "10000x SELECT x FROM foo took 10ms longer" conclusions are missing the point more often than not .
I can't provide you with solid benchmarks and the outcome depends on how the surrounding application handles the data but even synthetic tests usually only show differences so negligible that you better spend your time on optimizing your queries, the MySQL server, the network, ... instead of worrying about PDO's raw performance. Let alone security and error handling ...
My observation is that PDO seems to be less tolerate of many consecutive connections - that is connections being created in a loop. I know this is bad practice it the first place. When I was using mysql_* my looped queries seemed to be reasonably fast. However when I switched to PDO I noticed much longer response times for these types of queries.
TL;DR; - If you switch to PDO and you call queries in a PHP loop you may need to rewrite the application to call one single query rather than many consecutive queries.

Categories