mysqli vs mysql-performance and usage of mysqli is complicated - php

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.

Related

Questions about about PDO & MySQL best practices

I have many questions about PDO ...
Should I use prepare() only when I have parameters to bind? When I need to do a simple query like select * from table order by ... should i use query()?
Should I use exec() when I have update and delete operations and need to get the number of rows affected, or should I use PDOStatement->rowCount() instead?
Should I use closeCursor when I do insert, update and delete, or only with select when I need to do another select?
Does $con = NULL; really close the connection?
Is using bindParam with foreach to make multiple inserts a good point? I mean performance wise, because I think that doing (...),(...) on the same insert is better isn't it?
Can you provide me some more information (URL) about performance points when using PHP PDO MySQL? If someone has another hint it would be really useful.
When I was developing the DB layer in Zend Framework 1.0, I made it use prepare/execute for all queries by default. There is little downside to doing this.* There's a little bit of overhead on the PHP side, but on the MySQL side, prepared queries are actually faster.
My practice is to use query() for all types of queries, and call rowCount() after updates. You can also call SELECTROW_COUNT().
CloseCursor is useful in MySQL if you have pending rows from a result set, or pending result sets in a multi-result set query. It's not necessary when you use INSERT, UPDATE, DELETE.
The PDO_mysql test suite closes connections with $con=NULL and that is the proper way. This won't actually close persistent connections managed by libmysqlnd, but that's deliberate.
Executing a prepared INSERT statement one row at a time is not as fast as executing a single INSERT with multiple tuples. But the difference is pretty small. If you have a large number of rows to insert, and performance is important, you should really use LOAD DATA LOCAL INFILE. See also http://dev.mysql.com/doc/refman/5.6/en/insert-speed.html for other tips.
You can google for "PDO MySQL benchmark" (for example) to find various results. The bottom line, however, is that choosing PDO vs. Mysqli has no clear winner. The difference is slight enough that it diminishes relative to other more important optimization techniques, such as choosing the right indexes, making sure indexes fit in RAM, and clever use of application-side caching.
* Some statements cannot run as prepared statements in MySQL, but the list of such statements gets smaller with each major release. If you're still using an ancient version of MySQL that can't run certain statements with prepare(), then you should have upgraded years ago!
Re your comment:
Yes, using query parameters (e.g. with bindValue() and bindParam()) is considered the best methods for defending against SQL injections in most cases.
Note that there's an easier way to use query parameters with PDO -- you can just pass an array to execute() so you don't have to bother with bindValue() or bindParam():
$sql = "SELECT * FROM MyTable WHERE name = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute( array("Bill") );
You can also use named parameters this way:
$sql = "SELECT * FROM MyTable WHERE name = :name";
$stmt = $pdo->prepare($sql);
$stmt->execute( array(":name" => "Bill") );
Using quote() and then interpolating the result into a query is also a good way to protect against SQL injection, but IMHO makes code harder to read and maintain, because you're always trying to figure out if you have closed your quotes and put your dots in the right place. It's much easier to use parameter placeholders and then pass parameters.
You can read more about SQL injection defense in my presentation, SQL Injection Myths and Fallacies.
Most of questions can be answered with just common sense. So, here I am.
It doesn't matter actually.
Abolutely and definitely - NO. Exec doesn't utilize prepared statements. That's all.
Doesn't really matter. If you ever need this, your program architecture is probably wrong.
You can easily test it yourself. A personal experience is always preferred.
The difference considered to be negligible. However, if your multiple inserts being really slow (on INNODB with default settings for example) you have to use a transaction, which will make them fast again.
There is NONE. PDO is just an API. But APIs aren't related to performance. They just translate your commands to the service. It's either your commands or service may affect performance, but not mere API.
So, the rule of thumb is:
it's query itself that affects performance, not the way you are running it.

Using Mysqli: Is there a way to not have to connect to the database every single query?

I have just begun working with MYSQLi instead of MYSQL, and I have run into a huge annoyance: having to connect to the database every single query and such. Why do I have to do this now when I didn't in old MYSQL? Or is there a way not to have to do this?
A couple examples:
Mysql:
mysql_query("SELECT id FROM table");
Now in Mysqli I always have to do:
mysqli_query($db, "SELECT id FROM table");
also I have to do this with:
mysqli_last_id($db);
and
mysqli_real_escape_string($db);
I have tried to find the answer to this all night, but I can't find anything.
There are some things to clarify
You don't have to connect every time. Connecting to database is different thing, one when you're calling mysqli_connect() and you should do it only once per application.
So, you're talking of just using connection resource variable.
Yes, you have to pass it in every function. Not a big deal, nothing to talk of.
The only issue could be with variable scope. Use global $db; inside a function.
Moving to mysqli just mechanically, using new functions old way makes absolutely no sense. If you want to keep using mysqli_real_escape_string in the application code - don't bother with transition at all and keep with mysql.
The only reason (quite weak though) for move - to use prepared statements.
Mysqli's support for prepared statements is awful
So, better quit mysqli and go for PDO
Nevertheless, using raw API functions, be it mysql, mysqli or PDO, is ugly. One have to adopt some abstraction library to be used in the application code instead.
Yeap, don't use mysql_* functions, they are deprecated. Use PDO instead
http://www.php.net/manual/es/pdo.construct.php
$pdo = new PDO(/* Connection options */);
$rows = $pdo->query("SELECT * FROM table")->fetchAll(PDO::FETCH_OBJ);
foreach ($rows as $row) {
print_r($row);
}
$pdo->query("INSERT INTO table SET field1 = 'value1'");
Give a try to DALMP Database Abstraction Layer for MySQL using PHP. is uses pure mysqli and connects to database only when needed, when possible get the results from the cache, with out touching the database.
Examples of using the cache can be found here Cache & prepared statements

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.

Which is fastest in PHP- MySQL or MySQLi?

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.

Categories