-3

I made a little quiz with PHP and MySQL. When the quiz is finished, the user receives this:

<p>
    Final Score:<?php echo $_SESSION['Score']; ?>
</p>

Then, I also wanted to put all the results in a table, so I tried this:

$sql = "INSERT INTO `Results` (Username, Score) VALUES ('$username', $score)";

But I don't know how to put this $_SESSION['Score'] = $score to insert the result into the table.

  • 1
    Not related to your question, but building SQL queries like that is incredibly dangerous. Please always use placeholder parameters when building queries. – Jonathan Hall May 16 '18 at 17:06
  • 1
    What @Flimzy is trying to say: **Your code is vulnerable to SQL injection and will be hacked** even if [you are escaping inputs!](https://stackoverflow.com/a/5741264/2595450) Use [Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead. Check: [How can I prevent SQL injection in PHP](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Spoody May 16 '18 at 17:07
  • Thank you, but I'm not actually building a website, i just have to show it once and that's it :) – Thomas Lazzaroni May 16 '18 at 17:08
  • Do you mean `$score = $_SESSION['score']` You question is a bit confused and unclear – RiggsFolly May 16 '18 at 17:13
  • Yes, that's what I'm trying to do, but if I write that, it tells me: Notice: Undefined variable: score in C:\xampp\htdocs\quizzer\final.php on line 38 – Thomas Lazzaroni May 16 '18 at 20:02

1 Answers1

0

As you mentioned that you're not actually building a website, so SQL injection vulnerability is fine you should be able to just do

$sql = "INSERT INTO `Results` (Username, Score) 
VALUES ('".$username."', '".$_SESSION['Score']."')";

This works by escaping the SQL string and inputting your variable

Edit --

Id just like to clarify in case anyone else sees this, this is not the way you should do SQL queries and it has many security vulnerabilities.

More info - http://php.net/manual/en/security.database.sql-injection.php

GiantJelly
  • 298
  • 2
  • 15