2

I'm trying to learn how to use PDO and I need help understanding something.

I keep reading that one of the biggest benefits of using PDO is that a it is much more efficient than mysql_* when making similar queries over and over again. I need to make a query that is exactly the same, except that the bound parameters change each time (but the structure of the query is the same). So, here's my question:

Should I call PDO::prepare() once and then inside my loop call execute() (passing the parameters array), or should I be calling PDO::preprare() every time the loop runs?

Thanks!

Nate
  • 26,164
  • 34
  • 130
  • 214

1 Answers1

3

Right out of the docs:

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

So you only call prepare once and call execute inside your loop.

Example out of docs:

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

http://www.php.net/manual/de/pdo.prepare.php

WolvDev
  • 3,182
  • 1
  • 17
  • 32