Question:
How to use PHP to display MySQL results in an HTML table?

To display MySQL results in an HTML table using PHP, you'll need to fetch the data from the MySQL database, loop through the result set, and generate HTML code to display the data in a table format. Here is how you can do that:


<?php

  $i = 0;

  $colNames = array();

  $data = array();

  while($row = ***_fetch_assoc($res)) //where $res is from the main query result not schema information

  {

     //get the column names into an array $colNames

     if($i == 0) //make sure this is done once

     {

        foreach($row as $colname => $val)

           $colNames[] = $colname;

     }


     //get the data into an array

     $data[] = $row;


     $i++;

  }


 ?>



replace the above code and it worked, simple and shorter

$data = array();

  while($row = mysql_fetch_assoc($res))

  {

     $data[] = $row;

  }


  $colNames = array_keys(reset($data))



Continued as before: Print the table

<table border="1">

 <tr>

    <?php

       //print the header

       foreach($colNames as $colName)

       {

          echo "<th>$colName</th>";

       }

    ?>

 </tr>


    <?php

       //print the rows

       foreach($data as $row)

       {

          echo "<tr>";

          foreach($colNames as $colName)

          {

             echo "<td>".$row[$colName]."</td>";

          }

          echo "</tr>";

       }

    ?>

 </table>



Test Result:

I have divided up the process of creating tables from that of retrieving data. They are now interdependent, and by adding static data to the arrays, you can test the creation of your tables without a database.


They can also be divided into distinct roles.


Answered By:> codingbiz

Credit:> Stackoverflow


Read more:

>CRUD Operation on Angular

>Complete guide on Life Cycle of Angular Component

>Adding a search filter inside the dropdown in AngularJS?

>>Building a web application with Angular and Firebase
Build Progressive Web Apps with Angular


Ritu Singh

Ritu Singh

Submit
0 Answers