Php on zend, how to escape a variable for a query?
13,825
Solution 1
Easy:
$db->quote($username);
So:
$username = $db->quote($username . '%');
$select = 'SELECT COUNT(*) AS num
FROM message m
WHERE m.message LIKE ' . $username;
$row = $db->fetchRow($select);
Solution 2
$sql = 'SELECT * FROM messages WHERE username LIKE ?';
$row = $db->fetchRow($sql, $username);
Reference: http://framework.zend.com/manual/en/zend.db.html
Solution 3
When working with a model you can use:
$bugs = new Bugs();
$row = $bugs->fetchRow($bugs->select()->where('bug_id = ?', 1));
Comments
-
Joseph almost 2 years
im doing some queries in Zend Framework and i need to make sure no SQL injection is possible in the next kind of formats. I can use mysql_escape(deprecated) and wont do all the work. If i try to use real_mysql_escape it wont be able to grab the conection with the database and i cant find how zend_filter would solve the problem.
The query im doing (simplied) have the next sintaxes:
$db = Zend_Registry::get('db'); $select = "SELECT COUNT(*) AS num FROM message m WHERE m.message LIKE '".$username." %'"; $row = $db->fetchRow($select);
What is the best way to prevent SQL INJECTION with this framework?
-
Gisheri about 10 yearswhen I use $db->quote on a string that I am inserting, it puts quotes into the string even in the database field. Do I have to trim it after i quote it, or am I using it incorrectly?
-
Andrea Mauro over 4 yearsThe % is missing in this example, could it work suffixing $username with '%'?