简体   繁体   中英

MySQL SELECT statement only returning one row

I know for certain that there are two rows of data in my table that meet the condition of the where clause, yet my coding is only outputting (echoing) one row. What am I doing wrong?

<?php


$connect= mysqli_connect("localhost", "root", "", "friends_list")
or die('error connecting with the database');

$query= "SELECT * FROM people WHERE age=19";

$result= mysqli_query($connect, $query)
or die('error querying the database');

$row= mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result))
{
echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"                             
}
mysqli_close($connect);

?>

You're swallowing the first row, and not doing anything with it; ie, change:

$row= mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result))

to:

while ($row = mysqli_fetch_array($result))
<?php
    $connect= mysqli_connect("localhost", "root", "", "friends_list")
    or die('error connecting with the database');

    $query= "SELECT * FROM people WHERE age=19";

    $result= mysqli_query($connect, $query)
    or die('error querying the database');

    while ($row = $result->fetch_assoc()){
        echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"                             
    }
    mysqli_close($connect);
?>

$result->fetch_assoc() will fetch everything that match the sql condition, and you can prevent further error like you did in the above. You can learn more here fetch_assoc() function

You're fetching the first row, but not doing anything with it, so this row is not fetched inside the while loop and therefore not outputted.

$row= mysqli_fetch_array($result); // remove this

while ($row = mysqli_fetch_array($result))
{
echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"                             
}

In this part:

$row= mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result))
{

You're skipping the first row. You fetch it, then in the while loop you fetch the next one immediately. You should remove the first fetch and have this only:

while ($row = mysqli_fetch_array($result))
{

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