2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Take a look at the Database class here: codereview.stackexchange.com/questions/26507/… \$\endgroup\$ – Dave Jarvis May 24 '13 at 19:26
  • \$\begingroup\$ Please post your calling code for each test. \$\endgroup\$ – Rob Apodaca May 27 '13 at 13:15
  • \$\begingroup\$ 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. \$\endgroup\$ – Dimitri May 28 '13 at 19:22
2
\$\begingroup\$

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?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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