<?php
$connect = mysqli_connect("localhost", "root", "", "hempbag_db") or die("Connection failed");
$query= "Select * from tbl_sales";
$ress = mysqli_query($connect, $query);
$result = mysqli_fetch_array($ress);
foreach($result as $a)
{
echo $a['ID']; // This doesnt print although i used fetch array
}
foreach($ress as $a)
{
echo $a['ID']; // This works why???? This variable has only query run
}
?>
为什么上层的foreach不运行而下层的却运行呢?谁能解释一下?
答案 0 :(得分:3)
运行查询时,它返回结果:
$ress = mysqli_query($connect, $query);
var_dump($ress); // You will see it's a result.
此时$ress
仅包含您刚刚查询的结果。这样想吧:
$ress
)。现在,您无法循环浏览,无法执行任何操作。mysqli_fetch_array()
)。您的助手去拿了,然后把饼干还给您。简而言之,mysqli_query
仅返回Result#1
之类的对象。 mysql可以从Result#1
告诉您返回了多少行mysql_num_rows(Result#1)
,如果是选择查询,则可以获取实际数据:mysqli_fetch_array(Result#1)
。
现在进行推理:性能。假设您不想要1000个饼干,而只是想知道他们是否有1000个饼干。如果她带着所有的饼干盒回来了,而你不得不自己数一算,那就困难得多了。相反,她可以用那张纸来确定您可以订购多少盒。传输的数据更少,效率更高。
请注意,在更高版本的php中,它们使结果变得可迭代,这意味着如果您尝试遍历它,它将自动对该结果调用mysqli_fetch_array,并返回结果。
此外,mysql_fetch_array将从数据库返回一行,并且无法通过foreach循环通过。也许您正在考虑mysqli_fetch_all?这将返回所有行并可以循环通过(尽管与在mysqli_fetch_array中使用while循环相比,性能稍差)
答案 1 :(得分:1)
$ress = mysqli_query($connect, $query);
此行返回的结果集为 Traversable 。因此,您的第二个foreach效果很好。
而下一行(mysqli_fetch_array)一次获取一行并将其设为数组。
$result = mysqli_fetch_array($ress); // Suppose you have 3 rows, Now cursor is at row 1
echo $result["ID"]; // this will print FIRST row's ID
$result = mysqli_fetch_array($ress); // Now cursor is at row 2
echo $result["ID"]; // this will print SECOND row's ID.
$result = mysqli_fetch_array($ress); // Now cursor is at row 3
echo $result["ID"]; // this will print THIRD row's ID.
回显所有ID
while($result = mysqli_fetch_array($ress)) {
echo $result["ID"];
}