当我将 SQL 查询的结果保存在变量中(在 $test2 中的代码中)时,该变量在 while 循环之外为空。为什么?
通常在该循环内定义变量是有效的(参见 $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?
最佳答案
您将覆盖每次循环迭代中的变量。将它们全部保存到数组中并查看结果:
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);
关于php - 无法在 while 循环之外访问 SQL 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23911703/