Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm having some issues understanding why PDO is 6X slower executing a query than the depreciated MySQL query function. Here's my code:

$conn = new PDO('mysql:host=localhost;dbname=work', 'root', 'Montreal');

protected function query_s($table, $col = '*', $where_col , $where, $return_col)
{

              $q = $conn->query("SELECT $col FROM $table WHERE $where_col='".$where."' LIMIT 1");
              $f = $q->fetch();
              $result = $f[$return_col];
              return $result;

}

Which retrieves 1 piece of information for a specific column.

The old code:

protected function query_s($table, $col = '*', $where_col , $where, $return_col)
{

    $SQL = mysql_query("SELECT $col FROM ".$table." WHERE $where_col='$where' LIMIT 1") or die(mysql_error());
            $data = mysql_fetch_array($SQL);
            $this->query_rows = mysql_num_rows($SQL);

            return $data[$return_col];  
}

As soon as I run the PDO version in a while loop through a database search (user tries to find something), it takes almost 6 seconds to retrieve 50 rows... Normally, it would take around 0.02 seconds with the MySQL function

I'm fairly new with PDO and I'm trying to write new code with it. I'm missing something here.

share|improve this question
Take a look at the Database class here: codereview.stackexchange.com/questions/26507/… – Dave Jarvis May 24 at 19:26
Please post your calling code for each test. – Rob Apodaca May 27 at 13:15
What I'm noticing is that I have to create a completely separate class to call my every query. I also noticed that making the connection within a class' method is A LOT slower than making the connection within the __construct() function... I'm quite confused. – Dimitri May 28 at 19:22

1 Answer

Change your connection string from host=localhost to host=127.0.0.1, for some reason PDO is slow at resolving the host name, just when using PDO always use the IP address of the server.

Also why are you fetching one row at a time when you need 50?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.