mgeezy
mgeezy

Reputation: 23

Increment mysql value with ++ from codeigniter controller

I am trying to have my function increment by 1 a value in mysql, but it only works for once - from zero to 1. Then it won't increment. I have noticed that I need to add (int) in order to get it do this, so I guess there is something to do with data type. Do you have any hints?

$mod_seq = $this->db2->query("select mod_sequence from tbl_release_info where release_id = '$release_id';");
$current_modsequence = (int)$mod_seq++;

$update_query_release_info = "update tbl_release_info set mod_sequence = '$current_modsequence' where release_id = '$rid';

Upvotes: 0

Views: 181

Answers (2)

Michael Krikorev
Michael Krikorev

Reputation: 2156

The query in your question returns the number of rows, not the value you want from mod_sequence. Try this instead:

$query = $this->db2->query("select mod_sequence from tbl_release_info where release_id = '$release_id';");

$row = $query->row();
  if (isset($row)) {
    $mod_seq = $row->mod_sequence;
  }
$mod_seq++;
$update_query_release_info = "update tbl_release_info set mod_sequence = '$mod_seq' where release_id = '$rid';

If the datatype of mod_sequence is not an integer, type cast it:

$mod_seq = (int)$row->mod_sequence; 

Or like this:

$mod_seq = intval($row->mod_sequence);

EDIT: @RiggsFolly nailed the most elegant solution, by far, in a single query :-) https://stackoverflow.com/a/42194758/1363190

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94662

You can do that with just SQL and in a single query like this

$this->db2->query("update tbl_release_info 
                     set mod_sequence = mod_sequence + 1 
                   where release_id = '$rid'");

Upvotes: 1

Related Questions