Displaying data from MYSQL in webpage

Displaying MySQL data on the page is done by using php's mysqli() functions. To display data on the webpage first we need to connect to Mysql database server, extract data from  it and then display that data on the webpage.  Now lets see the example php code :

showData.php
<!DOCTYPE html>
<html>
<head>
  <style>
    table, th, td {
      min-width: 100px;
      text-align: center;
      padding: 5px;
      border: 1px solid gray;
    }
  </style> 
</head>
<body>
  <h2>Employee Information :</h2>

<?php

  $server = "localhost";
  $username = "root";
  $password = "";
  $dbName = "mydb";

  $connection = mysqli_connect($server, $username, $password, $dbName);

  $sql = "SELECT * from employee";
  $result = mysqli_query($connection, $sql);

  $row = mysqli_fetch_all($result, MYSQLI_ASSOC);
  $rowcount = mysqli_num_rows($result);

  // iterate through each row
  echo "<table>
        <tr>
          <th>Employee Id</th>
          <th>Employee Name</th>
          <th>Salary</th>
          <th>Address</th>
          <th>PIN</th>
        </tr>";

  for($i = 0; $i < $rowcount; $i++) {
    echo "<tr>";
    echo "<td>" . $row[$i]["EmpId"] . "</td>";
    echo "<td>" . $row[$i]["EmpName"] . "</td>";
    echo "<td>" . $row[$i]["Salary"] . "</td>";
    echo "<td>" . $row[$i]["Addr"] . "</td>";
    echo "<td>" . $row[$i]["PIN"] . "</td>";
    echo "</tr>";
  }

  echo "</table>";

  mysqli_close($connection);

?>

</body>
</html>
Output :


Explanation :

At the above code exmaple showData.php, first we connect to the mysql server using  mysqli_connect() function and then fatch all the data by mysqli_fetch_all() function. At line number {} The mysqli_num_rows() function is used to count the number of rows on returned result. Then we use for loop at line {} to print all rows line by line within HTML table format.

Next Topic :