1

Is there a way in Zend to increment an integer, held in a MySQL column, by 1?

Thanks

edit:

My current code is like:

$row = $this->find($imageId)->current();
$row->votes = // THIS IS WHERE I WANT TO SAY INCREMENT
$row->save();
Phil
  • 157,677
  • 23
  • 242
  • 245
edwinNosh
  • 389
  • 3
  • 9
  • 16

3 Answers3

19

Yes there is. Here's an example using products and incrementing a quantity field:

$table     = 'products'; 
$data      = array('prd_qnty' => new Zend_Db_Expr('prd_qnty + 1')); 
$where[] = $db->quoteInto('pr_id = ?', $this->pr_id); 
$db->update($table, $data, $where);
RDL
  • 7,865
  • 3
  • 29
  • 32
  • Is the downvote for my old answer or new one? I'm pretty sure the new one is correct, no? – RDL Mar 23 '11 at 04:56
  • Yes, `$row->votes++;` would be the way to go. In future it helps to show related code in your question so we can guide you to the best possible solution. – RDL Mar 23 '11 at 05:14
5

votes++ does not protect against race conditions from other requests, that's why it is desirable to have a database solution.

For example: imagine two requests come in at almost the same time

1st request loads object - votes is 500
2nd request loads object - votes is 500
1st increments value in memory - votes is 501
2nd increments value in memory - votes is 501
1st saves to db - votes is 501
2nd saves to db - votes is 501 (should be 502)
Steve L
  • 51
  • 1
  • 2
0

Might I offer the following suggestion

$row->votes++;
Phil
  • 157,677
  • 23
  • 242
  • 245