如何将结果输入变量MYSQL

时间:2014-04-08 07:43:09

标签: php mysql arrays

我有以下PHP脚本。如何获得正确的结果。每个查询只应返回一个数字。在这种情况下我需要rank。我也想知道如何将这两个查询合并为一个语句。

function getRankings($country, $deviceid)
{

$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";

$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score  AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";

$resultWorld =  mysql_query($queryWorld) or die(mysql_error());  
$rowWorld = mysql_fetch_row($resultWorld);
$resultCountry =  mysql_query($queryCountry) or die(mysql_error());
$rowCountry = mysql_fetch_row($resultCountry);

$arr = array();
$arr[] = array("WorldRanking" => $rowWorld[0], "CountryRanking" => $rowCountry[0]);
echo json_encode($arr);         
}

如果我将查询单独输入MYSQl,我会得到正确的答案。但echo产生了

[{"WorldRanking":null,"CountryRanking":null}]

应该是

[{"WorldRanking":"4","CountryRanking":"1"}]

我想我需要获得rank的价值,但我不知道如何。

2 个答案:

答案 0 :(得分:1)

尝试这样的代码,但我不知道这段代码是否正确:

function getRankings($country, $deviceid)
{

$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";

$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score  AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";

$resultWorld =  mysql_query($queryWorld) or die(mysql_error());  
while ($rowWorld = mysql_fetch_row($resultWorld)){
$value1 = $rowWorld['filedname1'];
}
$resultCountry =  mysql_query($queryCountry) or die(mysql_error());
while($rowCountry = mysql_fetch_row($resultCountry)){
$value2 = $rowWorld['filedname2'];
}

$arr[] = array("WorldRanking" => $value1, "CountryRanking" => $value2);
print_r($arr);        
}

答案 1 :(得分:0)

<?php
function getRankings($country, $deviceid)
{

$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID=$deviceid ORDER BY rank LIMIT 1";

$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score  AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID=$deviceid ORDER BY rank LIMIT 1";

$resultWorld =  mysql_query($queryWorld) or die(mysql_error());  
$no_of_results_in_resultWorld = mysql_num_rows($resultWorld);
if($no_of_results_in_resultWorld > 0){
    $rowWorld = mysql_fetch_row($resultWorld);
}

$resultCountry =  mysql_query($queryCountry) or die(mysql_error());
$no_of_results_in_resultCountry = mysql_num_rows($resultCountry);
if($no_of_results_in_resultCountry > 0){
    $rowCountry = mysql_fetch_row($resultCountry);
}

$arr = array();
$arr[] = array("WorldRanking" => $rowWorld[0], "CountryRanking" => $rowCountry[0]);
echo json_encode($arr);         
}

检查是否返回结果。