0

Incrementing a column of type Int directly in MySQL

I had a problem where I wanted to increase the value of the votes column each time a nominee received a vote. As I’m not entirely proficient in SQL I figured I would have to first perform a select, save the original value in a variable, increment that variable then perform an update to the column. I thought that there must be an easier way so I referred to MySQL a Pocket Reference which advised me on page 88 of various Arithmetic Operators that are available in the MySQL syntax. Seeing that this looked like the correct way to approach the issue I googled for Increment A Mysql Column and came up with an article at KnowledgeSutra which advised me that the following was the best approach:

UPDATE MyTable SET MyColumn=MyColumn+1 Where MyID=123

I then adapted this to my problem and came up with:

public function addVote($nominationId){
$query = "UPDATE Nominations SET Votes=Votes+1 Where ID=".$nominationId;
$this->db->query($query);
return $this->db->getResult();
}

This is now perfectly updating the number of votes for a given user.

Jason Edwards