Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

sql - Increment field of mysql database using codeigniter's active record syntax

I have the following php-codeigniter script which attempts to increment a field of a record using active-record syntax:

$data = array('votes' => '(votes + 1)');
$this->db->where('id', $post['identifier']);
$this->db->update('users', $data);

This produces the following SQL:

"UPDATEusersSETvotes= '(votes + 1)' WHEREid= '44'"

Which doesn't run, but this SQL does do what I'm looking for: "UPDATEusersSETvotes= (votes + 1) WHEREid= '44'"` <--Note the lack of quotes around (votes + 1)

Does anyone know how to implement this type of query with codeigniter's active record syntax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do as given below:

$this->db->where('id', $post['identifier']);
$this->db->set('votes', 'votes+1', FALSE);
$this->db->update('users');

The reason this works is because the third (optional) FALSE parameter tells CodeIgniter not to protect the generated query with backticks ('). This means that the generated SQL will be:

UPDATE users SET votes= votes + 1 WHERE id= '44'

If you notice, the backticks are removed from '(votes+1)', which produces the desired effect of incrementing the votes attribute by 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...