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));
Share:
13,825
Joseph
Author by

Joseph

Im just a hacker trying to be a better hacker

Updated on June 21, 2022

Comments

  • Joseph
    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
    Gisheri about 10 years
    when 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
    Andrea Mauro over 4 years
    The % is missing in this example, could it work suffixing $username with '%'?