我写了以下脚本。我的意图是做以下两件事:
- 让用户看到 的当前值
$score
。 - 让用户
$score
通过按“分数!”来增加 1。按钮。
的值$score
存储在数据库中。
只有一个问题——当我点击“得分!” 按钮, 的值$score
不会增加一 - 它会重置为零,无论原始值是多少。
<?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>