April 29, 2012

Query update result in huge unexpected number

Question by user1251004

I have some problems with my hiscore table. Some players have got a lot of points really fast, more then possible. I post two code below:

The first one is the one I currently use, which cause the problem:

$name = mysql_real_escape_string($_POST['name']); 
$set = mysql_real_escape_string($_POST['set']); 


if ($set == 1 && isset($_POST['score']))
{
    $score = mysql_real_escape_string($_POST['score']); 

    $query = mysql_query("UPDATE users SET totalScore=totalScore + '$score' WHERE username='$name'"); 

    if ($query) 
    {
        echo 'success'; 
    }
    else {
        echo 'error'; 
    }

}

I tried to cast the score as an int in the code below, but the update result is a huge number (4294967295) to be set as the totalScore. The totalScore is of type int(25) and I set attribute to unsigned so a player can’t end up on the minus side.

Please help
Thanks

$name = mysql_real_escape_string($_POST['name']); 
$set = (int)$_POST['set']; 


if ($set == 1 && isset($_POST['score']))
{
    $score = (int)$_POST['score']; 

    $query = mysql_query("UPDATE users SET totalScore=totalScore + $score WHERE username='$name'"); 

    if ($query) 
    {
        echo 'success'; 
    }
    else {
        echo 'error'; 
    }

}

Answer by Starx

Its because you are adding a integer onto propably an integer datatype. There is no need of quotes and escaping, if you make sure the input is integer (which you are already doing)

"UPDATE users SET totalScore=totalScore + $score WHERE username='$name'" LIMIT 1;

Only you are updating the query based on the name, You might need to LIMIT the execution.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!