如何在 php 中按行迭代 mysql 查询
好的,所以我尝试查询我的数据库并选择具有特定值的所有行。 之后,我使用 mysql_fetch_array() 将查询转换为数组,然后尝试使用 foreach 循环按行迭代获取的数组。
<?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'];
}
?>
尽管当我对pointsAvailable 列之外的任何列执行此操作时,例如名为“name”的文本类型列,它只返回一个字母。
如何逐行迭代返回的查询,并允许从当前行获取特定的数据列?
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.
<?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.
How do I iterate through a returned query row by row, and be allowed to fetch specific columns of data from the current row?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
或者使用 MYSQL_ASSOC 将允许您使用命名列
or using MYSQL_ASSOC will allow you to use named columns
是的,使用 mysql_fetch_array($result) 是正确的方法。
Yes using
mysql_fetch_array($result)
is the way to go.随着 PHP 7+ 成为新标准并且 mysql_fetch_array 被弃用,您将需要开始使用 mysqli_fetch_array。
面向对象风格
过程风格
您可以在 PHP Bible 上阅读有关此更改的更多信息。
https://www.php.net/manual/en/mysqli-result.fetch-array.php
With PHP 7+ becoming the new standard and mysql_fetch_array becoming deprecated you will need to start using mysqli_fetch_array.
Object-oriented style
Procedural style
You can read more about this change on the PHP Bible..
https://www.php.net/manual/en/mysqli-result.fetch-array.php