Select data with MySQLi (Object-oriented) and put result in an HTML table


SUBMITTED BY: henry1874w

DATE: June 21, 2017, 11:50 p.m.

FORMAT: Text only

SIZE: 892 Bytes

HITS: 235

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. table, th, td {
  6. border: 1px solid black;
  7. }
  8. </style>
  9. </head>
  10. <body>
  11. <?php
  12. $servername = "localhost";
  13. $username = "username";
  14. $password = "password";
  15. $dbname = "myDB";
  16. // Create connection
  17. $conn = new mysqli($servername, $username, $password, $dbname);
  18. // Check connection
  19. if ($conn->connect_error) {
  20. die("Connection failed: " . $conn->connect_error);
  21. }
  22. $sql = "SELECT id, firstname, lastname FROM MyGuests";
  23. $result = $conn->query($sql);
  24. if ($result->num_rows > 0) {
  25. echo "<table><tr><th>ID</th><th>Name</th></tr>";
  26. // output data of each row
  27. while($row = $result->fetch_assoc()) {
  28. echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " . $row["lastname"]. "</td></tr>";
  29. }
  30. echo "</table>";
  31. } else {
  32. echo "0 results";
  33. }
  34. $conn->close();
  35. ?>
  36. </body>
  37. </html>

comments powered by Disqus