Prepared StatementsΒΆ

The database driver supports prepared statements via the prepare method. This will return a StatementInterface object. A query can bind values in one of two ways (but not both at the same time):

  1. 0-based indexed via ? placeholders.
  2. named via :name placholders
$st = $driver->prepare('SELECT * FROM foo WHERE id=?');
$st = $driver->prepare('SELECT * FROM foo WHERE id=:id');

Parameters can be passed as the second argument:

$st = $driver->prepare('SELECT * FROM foo WHERE id=?', [42]);
$st = $driver->prepare('SELECT * FROM foo WHERE id=:id', [':id' => 42]);

Or they can be passed later via setParameter (by value) or bindParameter (by reference):

// by value
$st->setParameter(0, 42, Statement::INTEGER);
$st->setParameter(':id', 42, Statement::INTEGER);

// by reference
$st->bindParameter(0, $val, Statement::INTEGER);
$st->bindParameter(':id', $val, Statement::INTEGER);

$val = 42; // future calls to query/execute will use this value

The third parameter must be one of the following constants (AUTOMATIC is the default, if omitted):

  • Statement::AUTOMATIC
  • Statement::NULL
  • Statement::BOOLEAN
  • Statement::INTEGER
  • Statement::STRING
  • Statement::BLOB

Parameters can also be sent in bulk via setParameters (by value) or bindParameters (by reference). The third parameter will be an array of types; any omitted will be Statement::AUTOMATIC.

// by value
$st->setParameters([42], [Statement::INTEGER]);
$st->setParameters([':id' => 42], [':id' => Statement::INTEGER]);

// by reference
$st->bindParameters([&$val], [Statement::INTEGER]);
$st->bindParameters([':id' => &$val], [':id' => Statement::INTEGER]);

After setting or binding all parameters, call execute or query as appropriate. execute will return the number of affected rows, while query will return a RecordSetInterface.