-1

I have this code but in my opinion it's too many lines. I'm new into programming so that's why I have questions. I think there should be a shorter way to make it work without this if else loop, switch or is it ok like it's now?

if $total==21 then mysql_query("UPDATE user SET left = '20', $total==20 then left=19 and so on until the $total=1 and left=0.

if ($total==21 )
    {
        mysql_query("UPDATE `user` SET `left` = '20' WHERE `user` = 'user1' ") or die(mysql_error() );
    }   


else if ($total==20)
    {
        mysql_query("UPDATE `user` SET `left` = '19' WHERE `user` = 'user1' ") or die(mysql_error() );
    }   

    ....

else if ($total==1)
    {
        mysql_query("UPDATE `user` SET `left` = '0' WHERE `user` = 'user1' ") or die(mysql_error() );
    }   


else {

echo nl2br("0 left");

}

Merry Christmas !

usersubuser
  • 117
  • 13
  • 3
    yes, there is a shorter way: You can include variables to an update. So `$total-1` would be the value you wanna write to db. – Jeff Dec 25 '16 at 01:20
  • 2
    But please refrain from using `mysql_*` functions, as they are old, deprecated and removed in latest php. – Jeff Dec 25 '16 at 01:20
  • 1
    There is no need for the `nl2br` function there, as the content don't include any `\n` inside. – Dekel Dec 25 '16 at 01:21

2 Answers2

1

First, look at How can I prevent SQL injection in PHP?, and then something like:

if($total > 0 && $total < 22) {
    $left = $total - 1;
    // prepare("UPDATE `user` SET `left` = ? WHERE `user` = 'user1'")
    // bind_param('i', $left)
    // execute()
}
Community
  • 1
  • 1
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

You should be using PDO or Mysqli instead of the deprecated old mysql driver. This should solve your issue for now:

$total = (int) $total;
if ($total <= 0) {
    echo '0 left';
} else {
    $total--;
    mysql_query("UPDATE `user` SET `left` = '$total' WHERE `user` = 'user1' ") or die(mysql_error() );
}

Notice how I am hardcoding the variable to be an integer, this way it wouldn't be venerable to injections (in the event it comes from the client side).

Aziz Saleh
  • 2,687
  • 1
  • 17
  • 27