Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend_Db Question... updating an incrementor

Should this work? (increment the login count?)

// update the login count
$data = array(
   'logins' => 'logins + 1'
);

$n = $db->update('users', $data, 'user_id = '.$_userId);    
like image 795
MichaelICE Avatar asked Sep 20 '25 07:09

MichaelICE


1 Answers

$data = array(
   'logins' => new Zend_Db_Expr('logins + 1')
);

Also use quoting so you aren't as vulnerable to SQL injection:

$n = $db->update('users', $data, $db->quoteInto('user_id = ?', $_userId));

Re comment: Yes, in the case of the update() method, it assumes you're sending a literal value unless you use an object of type Zend_Db_Expr. You can test this yourself:

$db->getProfiler()->setEnabled(true);
$n = $db->update('users', $data, $db->quoteInto('user_id = ?', $_userId));
$qp = $db->getProfiler()->getLastQueryProfile();
echo $qp->getQuery() . "\n";

Any literal value you give in your $data array is parameterized so the query ends up looking like this:

UPDATE `users` SET `login` = ? WHERE user_id = 123

If you use an object of class Zend_Db_Expr, it knows to interpolate the string literally into the query, instead of parameterizing:

UPDATE `users` SET `login` = NOW() WHERE user_id = 123

Note that when you interpolate expressions like this, you are responsible for validation so you don't get security vulnerabilities.

like image 50
Bill Karwin Avatar answered Sep 22 '25 01:09

Bill Karwin