46

Should I use php PDO or normal mysql_connect to execute database queries in PHP?

Which one is faster?

One of the big benefits of PDO is that the interface is consistent across multiple databases. There are some cool functions for prepared statements too, which take some of the hassle out of escaping all your query strings. The portability of PDO is greater than mysql_connect.

So, should I use PDO for those reasons or stick to the traditional mysql_connect?

Jainendra
  • 23,305
  • 30
  • 116
  • 165
Imrul
  • 3,306
  • 5
  • 29
  • 27
  • 4
    Recently, I read a good article about PDO. I hope you will like it also. Link:: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+nettuts+%28NETTUTS%29 – Imrul Jun 24 '10 at 12:27
  • 2
    almost 4 years later than the original question was posted, now you should not use `mysql_*` functions as they are deprecated (see red box at the top of [`mysql_connect`](http://www.php.net/mysql-connect). – Carlos Campderrós Jun 17 '13 at 14:06
  • Another good article on the [deprecation of `mysql_*` functions](http://www.exchangecore.com/blog/update-deprecated-mysql-extension-pdo_mysql/) and also it describes how to go about implementing PDO if you're already using them. – Joe Meyer Jun 10 '14 at 14:15

12 Answers12

40

PDO is a bit slower than the mysql_* But it has great portability. PDO provides single interface across multiple databases. That means you can use multiple DB without using mysql_query for mysql, mssql_query for MS sql etc. Just use something like $db->query("INSERT INTO...") always. No matter what DB driver you are using.

So, for larger or portable project PDO is preferable. Even zend framework use PDO.

Bhavik Ambani
  • 6,357
  • 14
  • 52
  • 84
Sadi
  • 2,126
  • 3
  • 17
  • 31
  • Plus, small speed differences make no difference because it's easy to add more web servers with PHP's shared-nothing architecture. The database will perform the same regardless of whether you use PDO or the mysqli driver. – fabspro Jul 24 '12 at 05:34
  • 2
    Just wanted to note that PDO provides a level of abstraction at the driver level, which helps portability a lot. But if you end up writing SQL variations for one engine, you will need to modify your code to be able to port it to another DB (for example, see how to implement the MySQL `LIMIT` clause in MS SQL Server: http://stackoverflow.com/questions/603724/how-to-implement-limit-with-microsoft-sql-server) – Carlos Campderrós Jun 17 '13 at 14:10
17

Some quick timings indicate PDO is slightly faster at connecting.

$start = microtime(true);
for($i=0; $i<10000; ++$i) {

    try {
        $db = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage()."\n";
    }
    $db = null;
}

$pdotime = microtime(true) - $start;
echo "PDO time: ".$pdotime."\n";

$start = microtime(true);
for($i=0; $i<10000; ++$i) {
    $db = mysql_connect($host, $user, $password);
    if(!$db) {
        echo "Connection failed\n";
    }
    if(!mysql_select_db($schema, $db)) {
        echo "Error: ".mysql_error()."\n";
    }
    mysql_close($db);
}

$rawtime = microtime(true) - $start;
echo "Raw time: ".$rawtime."\n";

Gives results like

PDO time: 0.77983117103577
Raw time: 0.8918719291687

PDO time: 0.7866849899292
Raw time: 0.8954758644104

PDO time: 0.77420806884766
Raw time: 0.90708494186401

PDO time: 0.77484893798828
Raw time: 0.90069103240967

The speed difference will be negligible anyway; establishing a network connection will likely take a LOT longer than any overhead incurred by PDO, especially if the mysql server is on another host.

You mentioned all the reasons to use PDO yourself. Really, never use the mysql_* functions directly, either use PDO, or use some other library.

gnud
  • 73,015
  • 5
  • 56
  • 76
  • 4
    Interesting... But every mysql_cnnect has been closed by using mysql_close; though not a single PDO has been closed or unset... May be we should close the PDO too or do not close the mysql_connect; only then we may get more accurate result. You need some extra time to close the connection. – Sadi Sep 09 '09 at 21:58
  • 2
    The PDO object destructor is called (and disconnects) when $db is set to null. Have a look at the PDO documentation. – gnud Sep 10 '09 at 06:58
  • 1
    http://us2.php.net/manual/en/pdo.connections.php I am not sure if it is removed from memory at the moment you declare new connection for the same variable. – Sadi Sep 12 '09 at 04:17
  • 6
    just to let you know that your test ain't fair because the raw test selects a database while the PDO test doesn't. – mauris Jan 03 '10 at 22:39
  • +1 @thephpdeveloper Thank you for pint at the fairness :) All benchmark should use same procedure to show the real comparison. Even if PDO close the connection after $db=null, it supposed to be separate case. – Sadi Apr 03 '10 at 04:06
  • 1
    I tested the same thing with PDO odbc connection compared to standard odbc_connect and PDO was faster ~3 times. BUT, when i added just a simple "SELECT 100" query, to each loop (before the close), things changed very much. Now the standard odbc_connect+odbc_exec is faster ~30% then PDO version. It's not too realistic, I'd say, to just take the connection speed into account - you do it only once for many queries, no matter how far is the db server. – userfuser Nov 13 '12 at 11:06
  • 1
    Only flawed if you presume that the DB wasn't specificed in `$dsn`, which is usually what you'd expect to do. – LeonardChallis Jul 23 '14 at 11:03
11
  • With PDO you can uses binded params and that will prevent most sql injection attacks.
  • You can gain more speed using PDO prepared statements.
  • standard interface to all db backends
  • There are a bunch of useful methods (like the fetch* family)
Mikayla Maki
  • 463
  • 6
  • 18
10

I don't think speed is what people are looking for when they are using PDO -- I don't know if there is a difference, and I honnestly don't care : as long as I'm doing a couple of queries to a database when generating a page, a couple of milliseconds on the PHP side will not change anything.

There are two/three great things with PDO, compared to mysql_* :

  • More or less constant interface accross databases ; better than using mysql_*, pg_*, oci_*, ...
  • Object-Oriented API (mysqli_* has an OO-API, but not mysql_*)
  • Support new features of MySQL >= 4.1 (same as mysqli_*, but not mysql_*, again)

BTW : I'm generally using PDO -- either "by hand", or as it's integrated in / used by Zend Framework and/or Doctrine.


As a sidenote : Even if you are not going to use PDO, note that using mysqli instead of mysql is recommended.

See this page of the PHP manual, about that.

Pascal MARTIN
  • 374,560
  • 73
  • 631
  • 650
  • 2
    PDO doesn't allow us to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow us to use MySQL's support for Multiple Statements. So then, Should I use PDO? – Imrul Sep 09 '09 at 21:07
  • 4
    But whenever you need portability or your project/site is big enough, you should use PDO for better maintenance, cleaner code. Though it is possible to make clean code using mysql_*, you may have hard time to change driver etc. – Sadi Sep 09 '09 at 21:12
6

I did some performance testing to compare Mysqli functions to PDO functions using both prepared statements and regular direct queries (tested using select statements on Mysqlnd and MyISAM tables).

I found that PDO queries are just slightly slower than Mysqli, but only slightly. This makes sense since PDO used for this purpose mostly just a wrapper that calls Mysqli functions. The advantage to using PDO is that it makes it a little easier to migrate to a different database because the function names aren't specific to MySQL.

The real performance difference is in whether you use prepared queries. There is a large and significant performance penalty to using prepared queries. Other people who have tested them have found the same results.

The only time prepared queries are faster is if you are preparing a query once and then submitting it thousands of times with different data values. Otherwise, it's always faster to use mysqli::query() or PDO::query(). But it's important to be aware that those functions don't escape data values for you, so you need to remember to use mysqli::real_ escape_ string() or PDO::quote() on data variables.

orrd
  • 7,544
  • 3
  • 33
  • 28
  • Are you referring to PDO's emulated statement preparation, MySQL's native prepared statements, or both? – eggyal Mar 26 '14 at 23:24
4

I would generally recommend using PDO unless there is a specific reason you cannot. If there is no little difference between the two and you have no reason not to use PDO, I believe it would be better to get into the practice of using DB abstraction in your applications than going with mysql_* simply because it is there. I would say let best practice win.

Robert DeBoer
  • 1,655
  • 2
  • 16
  • 26
3
  • PDO is better than SQl
  • PDO And His Prepare Statement Provide Best Secure Code against SQL injection
  • PDO is Object Oriented ;)
  • PDO is compatible with some Databases Engine As Explained Before
  • MySQLl_* Is Deprecated and will be removed soon
  • PDO provide more functionality with less line of codes Example:

    Pdo

    1. Connect
    2. Check for "<" And ">" And "#" (This check for global uses)
    3. Prepare
    4. Execute
    5. Close

MySQL_*

  1. Connect
  2. Add Backslash
  3. Xsafe
  4. Check for "<" And ">" And "#" (This check for global uses)
  5. Query
  6. Close

both the same functionality but you compare for codes PDO is more Humanly Readable :) So what you think?

Jamil Hneini
  • 557
  • 3
  • 13
3

In both cases, you call the same mySQL server from the same Php server ... so you cannot notice a lot of difference.

If you want good performance, think about cache (memcache or simple Php file ...) and make a good data base structure (INDEX ...)

Thomas Decaux
  • 18,451
  • 2
  • 83
  • 95
  • i agree because if you have a situation where the mysql driver consumes considerable resources in comparision to the database statements themselves ... you should really think about what went wrong. – The Surrican May 29 '11 at 16:27
2

The mysql_connect function is deprecated as of PHP 5.5.0 and, as with most deprecated features, will be removed. Therefore, prefer using PDO_MySQL (or another alternative MySQLi ) over mysql_connect.

Source: http://php.net/manual/en/function.mysql-connect.php

Czar Pino
  • 5,858
  • 6
  • 29
  • 58
2

If performance isn't a "real problem" for you, you should use PDO. The performance differs by small margins, and PDO has a very nice and portable cross-database interface wich can save you some headaches in case you need to use several database drivers.

yoda
  • 9,912
  • 19
  • 61
  • 90
0

Some Advantages of PDO:

  1. Can Access multiple database.
  2. Provided many database driver to connect with different different database.
  3. When you switch from one database to another database, you need not to write all the code to connect with new database, just change the connection string and some query which are required for new database.
  4. It provides prepare statement which is a kind of template of query which compiled only once and can be executed as many times as you want, by just changing the attributes which is called place-holder.
  5. Easy and efficient General Operation like- Insert, update...etc.
Bowdzone
  • 3,651
  • 11
  • 39
  • 49
alex
  • 1
-1

PDO database connection code:

<?php
$dbhost = 'localhost';
$dbname = 'clsrepair';
$dbuser = 'root';
$dbpass = '';

try {
    $db = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e) {
    echo "Connection error: ".$e->getMessage();
}
?>

Normal MySQL database connection code:

<?php 
mysql_connect("localhost","root", "");
mysql_select_db ("clsrepair");
?>

or

 <?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'clsrepair';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
?>

MySQL database connection code easy but PDO has many advantage.

Amranur Rahman
  • 736
  • 13
  • 21