Increment a column in MySQL

2019-08-09 23:33发布

问题:

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

回答1:

Might I offer the following suggestion

$row->votes++;


回答2:

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


回答3:

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)