0

I'm trying to update a value of a column using the codeigniter query function like this:

    $this->db->query("UPDATE table SET val = val + 1 WHERE name = 'xxxxx');

Is there any way to get the result of this update in the same query function? I have to do a select query in order to do it and it's dangerous because of the amount of users this application is managing.

If there is another query in between the update and the select, the result would not be correct.

Thanks!

6
  • 2
    How about using a transaction? Commented May 15, 2013 at 14:50
  • Were you considered using autoincrement field? Commented May 15, 2013 at 14:50
  • mysql How can i use transactions in a codeigniter db->query function? It fails when I try it. Commented May 15, 2013 at 14:51
  • Sounds like it is some kind of counter for the row with name=xxxx, so an autoincrement doesn't look like it would help? Commented May 15, 2013 at 14:51
  • I cannot use an autoincrement field... :( Commented May 15, 2013 at 14:51

1 Answer 1

1

Use transaction and for update. This is an example from zend, which is a similar kind of db accessing thing:

$db->beginTransaction();
$val = $db->select()->forUpdate()->from('table', 'val')->orderBy('val DESC')->limit(1)->query()->fetchColumn();
$db->update('table', 'val = '.($val+1), 'name = "xxx"');
$db->commit()

The for-update with the transaction prevents another query interfering.

Learn more about for update here: http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html

and about codeigniter transactions here: http://ellislab.com/codeigniter/user-guide/database/transactions.html (thanks to @Nanne for that)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.