简体   繁体   English

SELECT * FROM`users`仅返回第一个用户

[英]SELECT * FROM `users` returns only first user

I have a php script: 我有一个PHP脚本:

$sql = $db->query("SELECT * FROM  `users`");
$row = $sql->fetch();
foreach($row as $value){
    echo $value . "<br>";
}

Database 'users' contains 29 records, but I'm getting this: 数据库“用户”包含29条记录,但是我得到了:

在此处输入图片说明

This is because you're only fetching one record. 这是因为您只获取一条记录。

Try your code like this: 尝试这样的代码:

$sql = $db->query("SELECT * FROM  `users`");
$row = $sql->fetchAll();
foreach($row as $value){
    print_r($value);
    echo "<br>";
}

this way you'll get an array of results, so you loop over the array instead of over the properties. 这样,您将获得一个结果数组,因此可以遍历该数组而不是遍历属性。

fetch() returns single elements. fetch()返回单个元素。 Instead try with fetchAll 而是尝试使用fetchAll

$row = $sql->fetchAll();

fetchAll — Returns an array containing all of the result set rows fetchAll —返回包含所有结果集行的数组

it will return an array hence, remove echo $value and use print_r($value) 它会返回一个数组,因此,删除echo $value并使用print_r($value)

fetch — Fetches the next row from a result set only 1 row fetch —从结果集中仅获取1行

mysql fetch() function fetches the next row from a result set only 1 row, whereas mysql fetchAll() function returns an array containing all of the result set rows. mysql fetch()函数仅从结果集的一行中获取下一行,而mysql fetchAll()函数返回一个包含所有结果集行的数组。

So use fetchAll() to get all the records from resultset, replace this line 因此,使用fetchAll()从结果fetchAll()获取所有记录,替换此行

$row = $sql->fetch();

with

$row = $sql->fetchAll();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM