简体   繁体   中英

PHP mysqli increase value

First off all, i need to say that im begginer on php, mysqli, but i want to learn. i am trying to build an quiz script wich store "SCORE" information into database.

I have the following "final.php" page script, wich collect and insert into database, the curent score of user. What i need is that i want to keep the current score from database "eg: 213" , and increase with curent session score wich will be "eg :10" , so total score after that will be "213(old) + 10(current) = 223(total)

 <?php $servername = "localhost"; $username = ""; $password = ""; $dbname = ""; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "UPDATE users SET scor='".$_SESSION['score']."' WHERE id=2"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close(); ?> 

Everything working fine with that code, but all what i need is that to increase score. Thank you to everyone for you patience and because you understand me that i am begginer :)

You can update the existing value in the database by adding your amount to it. There is no need to select the score first.

So in your example:

UPDATE users SET scor=scor + '".$_SESSION['score']."' WHERE id=2

This can be exploited by sql injection, but its out of the scope of the question.

您可以使用以下语句

$sql = "SELECT scor FROM users (UPDATE users SET scor= scor + '".$_SESSION['score']."' WHERE id=2)";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM