Contao does not support prepared statements

Due to the naming of methods in Contao’s Database Layer one might get the impression that you might use prepared statements in Contao. Sadly that is not true. The goal of prepared statements is that the Database‘ query compiler does not need to run over and over again for the same query. Due to the method names „prepare“ and „execute“ I assumed (as a bug report shows, other people did as well) that Contao would offer prepared statements.

So something like this:

$res = $this->Database->query("
    select k.id, count(t.id) as cnt
    from tl_lt_keys k
    left join tl_lt_translations t on t.pid = k.id
    group by k.id
");
$update = $this->Database->prepare("
    UPDATE tl_lt_keys
    SET translations = ?
    WHERE id = ?
");
while ($res->next())
{
    $update->execute($res->cnt, $res->id);
}

Won’t work. I do not understand this decision, but well there’s a bug report: https://github.com/contao/core/issues/3262 and it seems this behavior of Contao is the most normal thing in the world. So for now I use something like the following and PDO within Contao if required:

$dbUser = $GLOBALS['TL_CONFIG']['dbUser'];
$dbData = $GLOBALS['TL_CONFIG']['dbDatabase'];
$dbPass = $GLOBALS['TL_CONFIG']['dbPass'];
$dbHost = $GLOBALS['TL_CONFIG']['dbHost'];

$this->db = new \PDO(
    'mysql:dbname=' . $dbData . ';host=' . $dbHost, $dbUser, $dbPass
);
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'UTF8'");

It shouldn’t be that difficult to implement PDO in their Database class, though.

No Comments

Post a Comment