1

我写了以下脚本。我的意图是做以下两件事:

  1. 让用户看到 的当前值$score
  2. 让用户$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>
4

3 回答 3

5

因为您的查询是在单引号中,这使您的变量$scores成为文字单词 $scores。结果,您的数字数据类型(prob int)将其转换为零。

将您的查询更改为:

$query='UPDATE scores SET score_counter="'.$scores.'" WHERE score_id=1';

我使用连接来确保$scores在查询中使用的值而不是文字 $scores。

于 2012-08-01T19:12:05.687 回答
0

要在 PHP 字符串中使用变量插值,您需要使用双引号:

$query="UPDATE scores SET score_counter=$scores WHERE score_id=1";
于 2012-08-01T19:13:07.480 回答
0

代替

$query='UPDATE scores SET score_counter="$scores" WHERE score_id=1';

$query='UPDATE scores SET score_counter="' .$scores. '" WHERE score_id=1';

它以 $score 作为单词,在 DB 中不存在

于 2012-08-01T19:13:46.883 回答