Zend_Db and related classes
Zend_Db is the primary class used for accessing the database, but there is more: Zend_Db_Statement, Zend_Db_Select and Zend_Db_Tables.
What you should know about their methods
| Method | Behavior |
|---|---|
query(mixed $sql, ...) |
Uses prepared statements internally, but SQL Injection is still possible if $sql is dynamically created. |
fetchAll(string|Zend_Db_Select $sql, ...) |
All the fetch methods use prepared statements internally, but SQL Injection is still possible if $sql is dynamically created. |
insert(mixed $table, $bind) |
Uses prepared statements internally, so SQL Injection is not possible. |
update(mixed $table, $bind, ...) |
Uses prepared statements internally, but SQL Injection may be possible if $where is created dynamically. |
delete(mixed $table, ...) |
SQL Injection may be possible if $where is created dynamically. |
Note: even if you use prepared statements via Zend_Db methods, SQL Injection is still possible if the WHERE and ORDER BY clauses are wrongly written, so pay attention to them.
A quick tip for WHERE clauses
A short tip: you can use type casting to avoid SQL Injection in a WHERE clause where possible.
$sql = 'SELECT * FROM table WHERE id = ' . (int)$_POST['id'];
Frequently Asked Questions
What is the focus of this article? +
Following the earlier article about SQL Injection, this article makes a stronger argument for using Zend Framework to handle database access. Zend_Db is the primary class used for accessing the database, but there is more to it: Zend_Db_Statement, Zend_Db_Select, and Zend_Db_Tables.
Does Zend_Db's query() method protect against SQL injection? +
query() uses prepared statements internally, but SQL Injection is still possible if the $sql parameter passed to it is dynamically created.
What about fetchAll() and the other fetch methods? +
All of the fetch methods use prepared statements internally, but SQL Injection is still possible if the $sql is dynamically created.
Is insert() safe from SQL injection? +
Yes. insert() uses prepared statements internally, so SQL Injection is not possible with it.
What about update() and delete()? +
update() uses prepared statements internally, but SQL Injection may be possible if the $where clause is created dynamically. Likewise, with delete(), SQL Injection may be possible if $where is created dynamically.
Even with prepared statements, when can SQL injection still happen, and what tip helps avoid it in WHERE clauses? +
Even when using prepared statements via Zend_Db methods, SQL Injection is still possible if the WHERE and ORDER BY clauses are wrongly written, so these deserve special attention. A short tip mentioned is to use type casting to avoid SQL Injection in a WHERE clause where possible, for example: `$sql = 'SELECT * FROM table WHERE id = ' . (int)$_POST;`