How to Write SQL Queries in Latte?
Latte can also be useful for generating really complex SQL queries in a more readable way.
If constructing an SQL query involves numerous conditions and variables, writing it in Latte can significantly improve clarity. Here's a very simple example:
SELECT users.* FROM users
LEFT JOIN users_groups ON users.user_id = users_groups.user_id
LEFT JOIN groups ON groups.group_id = users_groups.group_id
{ifset $country} LEFT JOIN country ON country.country_id = users.country_id {/ifset}
WHERE groups.name = 'Admins' {ifset $country} AND country.name = {$country|escape} {/ifset}
Using $latte->setContentType()
, we tell Latte to treat the content as plain text (not HTML). Then, we prepare
an escaping function that uses the database driver to escape strings properly:
$db = new PDO(/* ... */);
$latte = new Latte\Engine;
$latte->setContentType(Latte\ContentType::Text);
$latte->addFilter('escape', fn($val) => match (true) {
is_string($val) => $db->quote($val),
is_int($val), is_float($val) => (string) $val,
is_bool($val) => $val ? '1' : '0',
is_null($val) => 'NULL',
default => throw new Exception('Unsupported type'),
});
The usage would look like this:
$sql = $latte->renderToString('query.sql.latte', ['country' => $country]);
$result = $db->query($sql);
This example requires Latte v3.0.5 or higher.