如何从php脚本中获取结果

时间:2013-07-02 14:34:27

标签: php mysql unity3d

已解决*即时尝试为正在进行的游戏创建高分数据库

我试图计算我的数据库中得分高于给定分数的用户数量,通过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脚本中,任何帮助将不胜感激

改变为工作版本,任何人都需要它

3 个答案:

答案 0 :(得分:1)

需要进行两项更改:

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

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

其次更改echo语句以使用您在SQL

中创建的列
echo $row['number'];

另请注意,不推荐使用mysql_函数,请改为使用mysqli functionsPDO functions

答案 1 :(得分: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.
}

答案 2 :(得分:0)

将此查询与别名

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

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

while ($row = mysql_fetch_assoc($result)) {
     echo $row['cnt'];
}