Doctrine DBAL Documentation, Release 2.1.0
4.2.1 DoctrineDBALTypes Conversion
If you don’t specify an integer (through a PDO::PARAM
*
constant) to any of the parameter binding methods but
a string, Doctrine DBAL will ask the type abstraction layer to convert the passed value from its PHP to a database
representation. This way you can pass \DateTime instances to a prepared statement and have Doctrine convert them
to the appropriate vendors database format:
<?php
$date = new \DateTime("2011-03-05 14:00:21");
$stmt = $conn->prepare("SELECT
*
FROM articles WHERE publish_date > ?");
$stmt->bindValue(1, $date, "datetime");
$stmt->execute();
If you take a look at Doctrine\DBAL\Types\DateTimeType you will see that parts of the conversion is dele-
gated to a method on the current database platform, which means this code works independent of the database you are
using.
Note: Be aware this type conversion only works with Statement#bindValue(),
Connection#executeQuery() and Connection#executeUpdate(). It is not supported to pass a
doctrine type name to Statement#bindParam(), because this would not work with binding by reference.
4.2.2 List of Parameters Conversion
Note: This is a Doctrine 2.1 feature.
One rather annoying bit of missing functionality in SQL is the support for lists of parameters. You cannot bind an
array of values into a single prepared statement parameter. Consider the following very common SQL statement:
SELECT
*
FROM articles WHERE id IN (?)
Since you are using an IN expression you would really like to use it in the following way (and I guess everybody has
tried to do this once in his life, before realizing it doesn’t work):
<?php
$stmt = $conn->prepare('SELECT
*
FROM articles WHERE id IN (?)');
// THIS WILL NOT WORK:
$stmt->bindValue(1, array(1, 2, 3, 4, 5, 6));
$stmt->execute();
Implementing a generic way to handle this kind of query is tedious work. This is why most developers fallback to
inserting the parameters directly into the query, which can open SQL injection possibilities if not handled carefully.
Doctrine DBAL implements a very powerful parsing process that will make this kind of prepared statement possible
natively in the binding type system. The parsing necessarily comes with a performance overhead, but only if you really
use a list of parameters. There are two special binding types that describe a list of integers or strings:
• \Doctrine\DBAL\Connection::PARAM_INT_ARRAY
• \Doctrine\DBAL\Connection::PARAM_STR_ARRAY
Using one of this constants as a type you can activate the SQLParser inside Doctrine that rewrites the SQL and flattens
the specified values into the set of parameters. Consider our previous example:
<?php
$stmt = $conn->executeQuery('SELECT
*
FROM articles WHERE id IN (?)',
array(array(1, 2, 3, 4, 5, 6)),
18 Chapter 4. Data Retrieval And Manipulation