Executing Raw SQL
Sometimes the built-in helpers aren’t enough.
That’s when you go raw – safely.
The db module gives you two weapons:
- – fire-and-forget raw SQL
- – raw SQL with proper parameter binding (the one you’ll use 99% of the time)
query_bind() – The Safe Choice
Always prefer this when user input is involved.
Named parameters (cleanest)
$sql = "SELECT * FROM users
WHERE age > :age
AND city = :city
ORDER BY joined_date DESC";
$data = [
'age' => 25,
'city' => 'London'
];
$users = $this->db->query_bind($sql, $data, 'object');Unnamed parameters (? placeholders)
$sql = "SELECT * FROM products
WHERE category = ?
AND price < ?";
$data = ['Electronics', 500];
$products = $this->db->query_bind($sql, $data, 'array');If any part of the query comes from user input → use query_bind() or one of the other database interaction methods. No exceptions.
query() – Only When You’re 100% Sure
Use this only for fully trusted, hard-coded queries (migrations, reporting, complex joins, etc.).
$sql = "SELECT u.name, COUNT(o.id) as total_orders
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id
ORDER BY total_orders DESC";
$top_customers = $this->db->query($sql, 'object');Never do this with user input from the outside world:
// DANGEROUS – instant SQL injection
$sql = "SELECT * FROM users WHERE email = '$email'";
$this->db->query($sql);Return Types
Both methods accept a $return_type parameter. For it's the third argument; for it's the second.
'object'→ rows returned as objects (the Trongate default)'array'→ rows returned as associative arrays- omit or
null→ no result set (perfect for INSERT/UPDATE/DELETE)
$this->db->query_bind($sql, $data); // just run it
$this->db->query_bind($sql, $data, 'array'); // force arraysDebug Mode Works Here Too
Turn on debug mode → both methods dump the fully bound SQL before execution. Lifesaver on hairy queries.
Need raw power or complex table joins? Use .
Need raw power and you wrote every character yourself? is fine.
For everything else, stick to the built-in helpers.
We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.
Share your thoughts in the Documentation Feedback.