Skip to content
Advertisement

Row from database not showing correctly except first row

The first row of this table is shown correctly and centered, while the other rows look like they are just being echo’d out instead of looking like they are part of the table.

This is the part of my code:

<table style="width:20%">
 <tr>
   <th>ID</th>
   <th>Nume</th>
   <th>Prenume</th>
 </tr>
 //fetching data from database
 <tr>
   <td><?php echo $data['id'];?></td>
   <td><?php echo $data['nume'];?></td>
   <td><?php echo $data['prenume'];?></td>
 </tr>
</table>

The code is supposed to add the written user to a database and display all of the users in a table next to it.

Any help is appreciated! Thanks! (whole code listed below)

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form action="index.php" method="post">
      <input type="text" name="nume" placeholder="nume" required>
      <input type="text" name="prenume" placeholder="prenume" required>
      <input type="submit" name="sub" value="Adauga in baza de date">
      <br>
    </form>
    <table style="width:20%">
      <tr>
        <th>ID</th>
        <th>Nume</th>
        <th>Prenume</th>
      </tr>
    <?php
      if(isset($_POST['sub']))
      {
        $pdo = new PDO("mysql:host=localhost;dbname=liamed", "root", "");
        $nume = $_POST['nume'];
        $prenume = $_POST['prenume'];
        $q = "insert into users(nume,prenume)values(:nume,:prenume)";
        $r = $pdo->prepare($q);
        $r->execute(array(":nume"=>$nume, ":prenume"=>$prenume));
      }
      $pdo = new PDO("mysql:host=localhost;dbname=liamed", "root", "");
      $query = "select * from liamed.users";
      $d = $pdo->query($query);
      foreach ($d as $data){

    ?>

    <tr>
      <td><?php echo $data['id'];?></td>
      <td><?php echo $data['nume'];?></td>
      <td><?php echo $data['prenume'];?></td>
    </tr>
  </table>
  </body>
<?php }
?>
</html>

Advertisement

Answer

You have the end of the table HTML included inside your loop hense the mess. Move that outside the loop and you should be sorted 🙂

foreach ($d as $data) :
?>

    <tr>
      <td><?php echo $data['id'];?></td>
      <td><?php echo $data['nume'];?></td>
      <td><?php echo $data['prenume'];?></td>
    </tr>
<?php
endforeach;
?>
    </table>
</body>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement