1

已解决* 我正在尝试为我正在开发的游戏创建一个高分数据库

我试图计算我的数据库中得分高于给定分数的用户数量,当通过 phpmyadmin 运行时查询工作正常,但我在从我的 php 脚本获取结果时遇到问题

查询 -$query = "SELECT COUNT(*) FROM得分WHERE得分> '$score'";

这是我到目前为止所拥有的

 <?php 
        $db = mysql_connect('localhost', 'user', 'user_pass') or die('Could not connect: ' . mysql_error()); 
        mysql_select_db('database') or die('Could not select database');

        // Strings must be escaped to prevent SQL injection attack. 
        $name = mysql_real_escape_string($_GET['name'], $db); 
        $score = mysql_real_escape_string($_GET['score'], $db); 
        $hash = $_GET['hash']; 


        $secretKey="mysecretkey"; # Change this value to match the value stored in the client javascript below 

        $real_hash = md5($name . $score . $secretKey); 
        if($real_hash == $hash) { 
            // Send variables for the MySQL database class. 
            $query = "SELECT COUNT(*) as cnt FROM `scores` WHERE `score` > '$score'";
            $result = mysql_query($query) or die('Query failed: ' . mysql_error()); 

            //echo $row['number'];
            while ($row = mysql_fetch_assoc($result)) {
                echo $row['cnt'];
            }
            mysql_result($result, 0);
        } 
?>

如果它有助于我试图将结果恢复到 unity3d 但相信我的问题出在 php 脚本中,任何帮助将不胜感激

更改为工作版本以防有人需要

4

3 回答 3

1

需要进行两项更改:

首先在您的 SQL 中使用 AS,以便在打印结果时使用列名。

$query = "SELECT COUNT(*) AS number FROM `scores` WHERE `score` > '$score'";

其次更改您的 echo 语句以使用您在 SQL 中创建的列

echo $row['number'];

附带说明一下 mysql_ 函数已被弃用,请考虑改用mysqli 函数PDO 函数

于 2013-07-02T14:40:07.193 回答
1
$query = "SELECT COUNT(*) FROM `scores` WHERE `score` > '$score'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result); //what is this for? 

while ($row = mysql_fetch_assoc($result)) {
echo $row[$score];//change $score to the field that you want to fetch.
}
于 2013-07-02T14:50:55.043 回答
0

将此查询与别名一起使用

$query = "SELECT COUNT(*) as cnt FROM `scores` WHERE `score` > '$score'";

你必须在这里传递列别名而不是变量名

while ($row = mysql_fetch_assoc($result)) {
     echo $row['cnt'];
}
于 2013-07-02T14:40:04.357 回答