简体   繁体   中英

SELECT * FROM `users` returns only first user

I have a php script:

$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:

在此处输入图片说明

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. Instead try with fetchAll

$row = $sql->fetchAll();

fetchAll — Returns an array containing all of the result set rows

it will return an array hence, remove echo $value and use print_r($value)

fetch — Fetches the next row from a result set only 1 row

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.

So use fetchAll() to get all the records from resultset, replace this line

$row = $sql->fetch();

with

$row = $sql->fetchAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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