php 如何通过php中的mysql查询逐行迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2285600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate by row through a mysql query in php
提问by AFK
Ok, So I am trying to query my database and select all rows that have a certain value. After that I turn the query into an array with mysql_fetch_array(), then I tried iterating by row through the fetched array using a for each loop.
好的,所以我正在尝试查询我的数据库并选择具有特定值的所有行。之后,我使用 mysql_fetch_array() 将查询转换为数组,然后尝试使用 for each 循环逐行迭代获取的数组。
<?php
$query = mysql_query("SELECT * FROM users WHERE pointsAvailable > 0 ORDER BY pointsAvailable Desc");
$queryResultArray = mysql_fetch_array($query);
foreach($queryResultArray as $row)
{
echo $row['pointsAvailable'];
}
?>
Though when I do this for any column besides the pointsAvailable column say a column named "name" of type text it only returns a single letter.
虽然当我对除 pointsAvailable 列之外的任何列执行此操作时,会说一个名为“name”的文本类型的列它只返回一个字母。
How do I iterate through a returned query row by row, and be allowed to fetch specific columns of data from the current row?
如何逐行迭代返回的查询,并允许从当前行获取特定列的数据?
回答by Trevor
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
or using MYSQL_ASSOC will allow you to use named columns
或使用 MYSQL_ASSOC 将允许您使用命名列
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("ID: %s Name: %s", $row["id"], $row["name"]);
}
回答by Vatsala
Yes using mysql_fetch_array($result)is the way to go.
是的,使用mysql_fetch_array($result)是要走的路。

