我无法在循环外获取查询的值

时间:2014-04-15 16:26:45

标签: php mysql for-loop

我使用PHP并执行mysql查询,并将此查询的结果保存在数组中。然后,我使用循环并进入循环我使用where子句中的数组值执行另一个mysql查询。没错,但如果我试图在循环外得到查询结果,我就不能这样做。 这是一个示例代码

$result=$mysqli->query("SELECT code FROM referee");
$i=0;
$arcode=array();
while($row=$result->fetch_array()){ 
    $arcode[$i]=$row["code"];
    $i++;
}
for($j=0;$j<sizeof($arcode);$j++){
    $result2=$mysqli->query("SELECT code, time FROM match where referee_code IN ($arcode[$j])");
}

/*Here I can't get the result values*/
$matcode=array();
$hour=array();
$k=0;
while($row2=$result2->fetch_array()){
     $matcode[$k]=$row2["code"];
     $hour[$k]=$row2["time"];
}

如果我把所有内容放在同一个循环中,我会重复结果(这段代码是我所有代码的一个例子,但其余部分的想法是相同的。)

2 个答案:

答案 0 :(得分:0)

您正在将结果集值覆盖为$result2

正确的方法是:

$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code, 
                                 time 
                            FROM `match` 
                           WHERE referee_code IN (SELECT code 
                                                    FROM referee)");
while ($row2 = $result2->fetch_array())
{
    $matcode[] = $row2["code"];
    $hour[] = $row2["time"];
}

您可以根据阵列的显示方式更改索引值。

match也是保留字。所以你必须将它包含在反引号中。

答案 1 :(得分:0)

如果您想打印完整数据,请尝试以下方法:

$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code, 
                                 time 
                            FROM `match` 
                           WHERE referee_code IN (SELECT code 
                                                    FROM referee)");
$completeData=array();
while ($row2 = $result2->fetch_array())
{
    $completeData[] = $row2;
}
print_r($completeData);

如果有帮助,请忘记接受答案:)

相关问题