September 15, 2019 admin

How to get data from MySQL database with PHP and put it in an HTML table – Code Explained

Here’s the php code I used to output from my database. You’ll need to put in the proper connections to change everything over to work for your app.

<table class="table table-striped table-responsive-md btn-table">
<!-- -->
  <thead>
    <tr>


      <th>Username</th>
      <th>Current Game</th>
      <th>In-Game Username</th>
      <th>Looking for</th>
      <th>Reputation Score</th>
      <th>Contact via</th>
    </tr>
  </thead>
<!-- -->
  <tbody>
    <!-- -->
    <tr>

      <?php
      $servername = "localhost";
      $username = "root";
      $password = "";
      $dbname = "gamerapp";

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
      }

      $sql = "SELECT username FROM userdata";
      $result = $conn->query($sql);

      if ($result->num_rows > 0) {
          // output data of each row
          while($row = $result->fetch_assoc()) {
              echo "<tr><td> " . $row["username"]. "</td></tr>";
          }
      } else {
          echo "0 results";
      }
      $conn->close();
      ?>
  </tbody>

</table>