Reputation: 593
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);
?>
Upvotes: 1
Views: 2341
Reputation: 29
<?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
Upvotes: 0
Reputation: 20705
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))
{
Upvotes: 0
Reputation: 38130
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))
Upvotes: 5
Reputation: 13361
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/>"
}
Upvotes: 0