Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter, increase database value by value contained in variable

I am using codeigniter, and I have the following function in my model to give points to the user. It is however not working, rather setting the points column to 0.

This is how it is written in the codeigniter manual. Therefore I have no clue why it is not working...

Thanks

function give_points($username,$points)
{
    $this->db->set('points', 'points + $points');
    $this->db->where('username', $username);
    $this->db->update('users'); 
    echo"done";
}
like image 904
Thomas Clowes Avatar asked Jul 31 '11 13:07

Thomas Clowes


2 Answers

I believe you have to tell CI specifically to not escape the text. I don't have a CI installation handy to test this in, but I think it was something like:

$this->db->set('points', 'points + ' . (int) $points, FALSE);
like image 91
Sid Avatar answered Oct 20 '22 10:10

Sid


Not sure this is the cause of your problem, but you are using single quotes, on the following lines :

$this->db->set('points', 'points + $points');

With this, the $points string will be injected as-is, literally, into your SQL query -- it's not its value that's going to be used.


If you want $points to be interpolated (so its value is put in its place, in that string), you must use double quotes :

$this->db->set('points', "points + $points");


For more informations about variable interpolation, see the Variables parsing section of the PHP Manual.

like image 41
Pascal MARTIN Avatar answered Oct 20 '22 10:10

Pascal MARTIN