I wrote the following script. My intention was to do the two following things:
- Let a user see the current value of
$score. - Let the user increment the
$scoreby 1 by pressing the “Score!” button.
The value of $score is stored in a database.
Only one problem — when I click the “Score!” button, the value of $score doesn’t get incremented by one — it gets reset to zero, regardless of what the original value is.
<?php
$page_title = "";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><?php print($page_title) ?></title>
</head>
<body>
<?php // Script number 1.2, filename show_score.php
// error handling
ini_set('display errors',1); // Let me learn from my mistakes!
error_reporting(E_ALL|E_STRICT); // Show all possible problems!
// Set page title.
$page_title = "Game Score";
// Connect to the database:
$link = mysql_connect('localhost','username','password');
mysql_select_db('game_scores',$link);
// Create database query that gets the value of the score_counter cell
$sql = 'SELECT score_counter FROM scores';
$result = mysql_query($sql,$link);
// Create a variable, $score_counter, that holds the array that
//is the result of the previous SQL query
$score_counter = mysql_fetch_array($result);
// You don't really want the whole array, just score_counter[0],
// so assign score_counter[0] its own variable, $score
$scores = $score_counter[0];
// Now that you've retrieved the current number of scores from the
// database, and extracted that number from an array and
// put it in its own variable, print it out on the screen.
echo 'The current number of scores is ' . $scores . ' scores.';
// Now let users add to the number of scores by clicking the "score" button.
if(isset($_POST['score'])){
// increment the number of scores:
$scores++;
// create the SQL query:
$query='UPDATE scores SET score_counter="$scores" WHERE score_id=1';
// run the SQL query:
mysql_query($query) or die("Cannot update");
}
?>
<H1>Score Counter</H1>
<p>Click to add one point.</p>
<form action ="show_score.php" method ="post">
<input type ="submit" name ="score" value="score">
</form>
</body>
</html>
Because your query is in single quotes which makes your variable
$scoresbecome the literal word $scores. As a result your number data type (prob int) is converting it to a zero.Change your query to this:
I used concatenation to make sure the value of
$scoreswas used in the query instead of of the literal word $scores.