无法在我的 while 循环之外访问 SQL 数据 [英] Cant access SQL data outside my while loop

查看:44
本文介绍了无法在我的 while 循环之外访问 SQL 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I save a result of a SQL query in a variable (in the code in $test2), the variable is empty outside the while loop. Why?

通常在该循环内定义变量是有效的(参见 $test1).SQL 查询也有效.

Generally defining varibales inside that loop works (see $test1). And the SQL query works too.

$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?

推荐答案

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

You are overwritting the variables in each loop itteration. Save them all to an array and look at the results:

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);

这篇关于无法在我的 while 循环之外访问 SQL 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆