0

I need to say that I'm a beginner on php, mysqli, but I want to learn. I am trying to build an quiz script which store "SCORE" information into database.

I have the following "final.php" page script, which collects and inserts into the database, the current score of user. What I need is that I want to keep the current score from database "eg: 213", and increase with current session score which 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 beginner.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 5
    Please read about [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection). Instead of building queries with string concatenation, use [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) with [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). See [**this page**](https://phptherightway.com/#databases) and [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) for some good examples. – Alex Howansky Feb 14 '19 at 17:54
  • The first thing you have to learn is to not publish your database credentials... Note that editing the question won't help; the password will still be visible in the history. Change it now. – Peter Feb 14 '19 at 18:00
  • Thank you for your answers guys, and for your patience. I am begginer, so an example can help me. Thank you alot – David Claudiu Feb 14 '19 at 18:00
  • some guys this days use SO as freelancer ( but it's free service ) – zerocool Feb 14 '19 at 18:02

2 Answers2

0

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.

blahy
  • 1,294
  • 1
  • 8
  • 9
0

you can use the following statement

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