Codeigniter, increase the value of the database by the value contained in the variable

I use codeigniter and I have the following function in my model to give points to the user. However, it does not work, instead of setting the column of points to 0.

This is how it is written in the codeigniter manual. Therefore, I do not know why it does not work ...

thanks

function give_points($username,$points) { $this->db->set('points', 'points + $points'); $this->db->where('username', $username); $this->db->update('users'); echo"done"; } 
+7
source share
3 answers

I believe that you should tell CI specifically not to avoid the text. I do not have a CI installation to test this, but I think it was something like:

 $this->db->set('points', 'points + ' . (int) $points, FALSE); 
+10
source

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

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

With this, the string $points will be entered literally into your SQL query - this is not its value that will be used.


If you want $points be interpolated (so its value is put in its place on this line), you should use double quotes:

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


For more information about the interpolation variable, see Variable Analysis in the PHP Manual.

+1
source

If there is a chance, always check the generated SQL query - I do not know how to do this with CI.

However, your set() looks erroneous.

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

$points be part of the string and was not expanded by the contents of $points due to the use of a single quote instead of a double quote - see the manual for strings in PHP.

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

Less than the best code is the one above because it defeats a possible SQL injection , depending on where $points originally comes from.

0
source

All Articles