Kevin Johnson
Kevin Johnson

Reputation: 51

How to print data from table?

Why does the following code only prints only one entry:

$result = mysqli_query($con,"SELECT * FROM verifications WHERE user='seriot'");
$row = mysqli_fetch_array($result);
echo date(DATE_RFC822);
echo "<br>";
echo "<br>";
echo "<b>".$row['firstname'] . " " . $row['lastname']."</b>";
echo "<br>";
while($row = mysqli_fetch_array($result)){
   echo $row['filepath']." ".$row['type']; 
   echo "<br>";
}

While this code will print all entries:

while($row = mysqli_fetch_array($result)){
  echo $row['filepath']." ".$row['type']; 
  echo "<br>";
}

I am trying to print the First Name and Last Name once and then all filepath and type entries until the next name.

Thank you, Kevin

Upvotes: 1

Views: 100

Answers (2)

Prix
Prix

Reputation: 19528

You can use it like this:

$result = mysqli_query($con,"SELECT * FROM verifications WHERE user='seriot'");
echo date(DATE_RFC822), '<br><br>';
$name = '';
while($row = mysqli_fetch_array($result))
{
    $current = $row['firstname'] . ' ' . $row['lastname'];
    if (empty($name) || $name != $current)
    {
        echo '<b>', $current, '</b><br>';
        $name = $current;
    }
    echo $row['filepath'], ' ', $row['type'], '<br>'; 
}

We initiate $name empty, and then we save the last matched name into $name and if $current is different than $name we print it again.

Upvotes: 2

Dante Ditan
Dante Ditan

Reputation: 34

you need to loop the $row['firstname'] and the $row['lastname'] to get all the result in the array. like this:

      $row = mysqli_fetch_array($result);
      while($row = mysqli_fetch_array($result)){
      echo "<b>".$row['firstname'] . " " . $row['lastname']."</b>";
      echo "<br>";
      echo $row['filepath']." ".$row['type']; 
      echo "<br>";
      }

Your code above will display only the last result in the mysql_fetch_array

         $row = mysqli_fetch_array($result);
         echo date(DATE_RFC822);
         echo "<br>";
         echo "<br>";
         echo "<b>".$row['firstname'] . " " . $row['lastname']."</b>";
         echo "<br>";

Upvotes: 0

Related Questions