无法在我的while循环之外访问SQL数据

时间:2014-05-28 12:32:08

标签: php mysql sql

当我在一个变量中保存SQL查询的结果时(在$ test2的代码中),该变量在while循环外面是空的。为什么呢?

通常在该循环中定义varibales有效(参见$ test1)。 SQL查询也可以。

$connection = new mysqli($servername,$username,$password,$dbname) or die("Error: " . mysqli_error($connection));
$query = "SELECT * FROM Table ORDER BY `id` ASC";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_object($result)) {
    $test1 = "some text";
    $test2 = $row->id;
    echo $row->id // Output is the id -> works
}
echo $test1; // Output is "some text" -> works
echo $test2; // Output is nothing -> doesn't work. Why?

2 个答案:

答案 0 :(得分:2)

$row = mysqli_fetch_array($result)返回数组

您正在使用$test2 = $row->id;作为对象

答案 1 :(得分:2)

您正在覆盖每个循环迭代中的变量。将它们全部保存到数组中并查看结果:

while($row = mysqli_fetch_object($result)) {
    $test1[] = "some text";
    $test2[] = $row->id;
    echo $row->id // Output is the id -> works
}
print_r($test1); 
print_r($test2);