I’ve created a little weekly trivia game for my website. Basically its five questions, then at the end the user can add their score to a scoreboard.
The problem is that I want the scores to carry from week to week and cumulate. So let’s say you got 4 points one week, then 5 points the next. I want the scoreboard to reflect you have 9 points.
So I created a small form with an i
nvisible field that has the users score, a field for the username, and a field for the e-mail address. Next week, when the user takes the quiz again, I want their score to be updated if the username and e-mail match a record in the database. If no record does match, I want an entry to be created.
Here’s the script I came up with, however, it doesn’t work (which doesn’t surprise me, I’m pretty new to PHP/MySQL)
$name = $_POST['name']; //The Username
$score = $_POST['submitscore']; //The users score (0-5)
$email = $_POST['email'];//Users email address
$date = date("F j, Y, g:i a");//The date and time
if($name != '') {
$qry = "SELECT * FROM scoreboard WHERE name='$name'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$sum = ($row['SUM(score)']+$score);
"UPDATE scoreboard SET score = '$sum' WHERE name = '$name'";
}
else
$q = mysql_query("INSERT INTO scoreboard (`name`, `email`, `date`, `score`) VALUES ('$name', '$email', '$date', '$score');");
@mysql_free_result($result);
}
else {
die("Query failed");
}
}
My table scoreboard looks like this
id……..name……..email………..date………..score
1……..J.Doe…..j.doe@xyz.com…..7/27/11………4
You’re looking for
INSERT... ON DUPLICATE KEYsyntaxAside:
Use mysql_real_escape_string!
EDIT
First, this doesn’t really work unless you have a column
SUM(SCORE):If you want the sum of a column, you need to put that in the MySQL query directly. If you just want the score for that row, however, you can use
$row['score']. If you need to add to an existing score you don’t need to select for the value (thanks to a1ex07 for pointing this out)