DFectuoso
DFectuoso

Reputation: 4897

Php on zend, how to escape a variable for a query?

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?

Upvotes: 10

Views: 14093

Answers (3)

Ben Bos
Ben Bos

Reputation: 2371

When working with a model you can use:

$bugs = new Bugs();
$row = $bugs->fetchRow($bugs->select()->where('bug_id = ?', 1));

Upvotes: 1

karim79
karim79

Reputation: 342655

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);

Upvotes: 19

Konstantin Tarkus
Konstantin Tarkus

Reputation: 38378

$sql = 'SELECT * FROM messages WHERE username LIKE ?';
$row = $db->fetchRow($sql, $username);

Reference: http://framework.zend.com/manual/en/zend.db.html

Upvotes: 14

Related Questions