开发者

Codeigniter, increase database value by value contained in variable [duplicate]

开发者 https://www.devze.com 2023-03-25 09:43 出处:网络
This question already has answers 开发者_StackOverflow社区here: Add a clause to a MySQL statement without quotes using CodeIgniter's Active Record functions
This question already has answers 开发者_StackOverflow社区here: Add a clause to a MySQL statement without quotes using CodeIgniter's Active Record functions (5 answers) Update the value of a field in database by 1 using codeigniter (3 answers) Closed last month.

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";
}


You have to tell CI specifically to not escape the text. Something like:

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


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.


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

However, your set() looks flawed.

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

Previously, $points was part of the string, and not expanded by the contents of $points, due to you using a single quote instead of a double quote - see the manual regarding strings in PHP.

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

A slighty better code is the one above, as it defeats possible SQL injection, depending on where $points originally comes from.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号