[英]Understanding mysqli_fetch_array()
Is there a way to make the code below cleaner? 有没有办法使下面的代码更整洁? I wanted to access the rows of $query4week
like this: $query4week[0]
. 我想像这样访问$query4week
的行: $query4week[0]
。 But mysqli_query()
returns an Object on which I don't know how to access its particular rows. 但是mysqli_query()
返回了一个我不知道如何访问其特定行的对象。 So, using fetch_array
and a for
loop I decided to create my own index. 因此,使用fetch_array
和for
循环,我决定创建自己的索引。
$sql2 = "SELECT * FROM meals ORDER BY RAND() LIMIT 7";
$query4week = mysqli_query($con, $sql2) or die(mysqli_error($con));
for ($i = 0; $result = mysqli_fetch_array($query4week, MYSQLI_ASSOC); $i++)
{
$meal4week[$i] = $result['meal'];
}
I am still learning PHP and yet quite weak with OOP topics, please be patient :-) 我仍在学习PHP,但在OOP主题方面却很弱,请耐心:-)
You shouldn't need a for loop if your fetching an associative array. 如果您获取关联数组,则不需要for循环。
$i = 0;
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
$meal4week[$i] = $row['meal'];
$i++;
}
Do it in this way 用这种方式做
$i = 0;
while ($result = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
$meal4week[$i] = $result['meal'];
$i++;
}
should work. 应该管用。
There are already some perfectly reasonable answers here, but this is a little long for a comment. 这里已经有一些完全合理的答案,但这需要一点评论。 If all you are creating is a numerically indexed array starting with index 0, you don't need to explicitly define the index. 如果创建的只是一个以索引0开头的数字索引数组,则无需显式定义索引。
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC)) {
$meal4week[] = $row['meal'];
}
should work just fine. 应该工作正常。 No $i
necessary. 无需$i
。
mysqli_query
returns you a resource which represents the query result. mysqli_query
您返回代表查询结果的资源。 You need to use the mysql_fetch_*
functions to iterate over the result row by row. 您需要使用mysql_fetch_*
函数逐行遍历结果。 So yes, you need some kind of loop, if you are interested in more than the first row. 因此,是的,如果您对第一行以外的内容感兴趣,则需要某种循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.