Display MySQL data in an HTML table using mysqli_fetch_array()

Description: Write a PHP program that reads all the records of the users table from the MySQL database and shows them in an HTML table. The newest user must come first.

Rules and hints:

  • Use the db-connection.php file and the users table from the PHP MySQL tutorial.
  • Use mysqli_query() and mysqli_fetch_array().
  • Sort the records by id, from the highest to the lowest.

PHP program to display MySQL data in an HTML table

<?php
require_once('db-connection.php');

$result = mysqli_query($conn, "SELECT * FROM users ORDER BY id DESC");
?>
<table border="1" cellpadding="6">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Mobile</th>
        <th>Email</th>
    </tr>
    <?php while ($user = mysqli_fetch_array($result)) { ?>
    <tr>
        <td><?php echo $user["id"]; ?></td>
        <td><?php echo htmlspecialchars($user["name"]); ?></td>
        <td><?php echo htmlspecialchars($user["mobile"]); ?></td>
        <td><?php echo htmlspecialchars($user["email"]); ?></td>
    </tr>
    <?php } ?>
</table>

Output:

IDNameMobileEmail
3Pankit9898979797pankit@example.com
2Sanjay9898969696sanjay@example.com
1Ram9898989898ram@example.com

How it works

  • ORDER BY id DESC sorts the records from the newest to the oldest.
  • mysqli_fetch_array() returns one row in each call, and returns null when there are no more rows, so the while loop stops.
  • Every value is printed with htmlspecialchars() to be safe from XSS.

The difference between the fetch functions is in mysqli_fetch_array() vs mysqli_fetch_object(). See also PHP : MySQL Select Data.


Learn more about the similar topics:
Tutorials
PHP MySQL Tutorial
PHP : MySQL Database
PHP : MySQL Connect
PHP : MySQL Create Database
PHP : MySQL Create Table
PHP : MySQL INSERT Statement
PHP : MySQL Select Data
Exercises & Assignments
Display MySQL data in an HTML table using mysqli_fetch_array()
Interview Questions & Answers
What is the difference between mysqli_fetch_array() and mysqli_fetch_object()?
How to Fix Incorrect format parameter error when importing large database in PHPMyAdmin?
In how many ways can we fetch data from a MySQL result set in PHP?
How to encrypt and decrypt data stored in a MySQL table?
What is the difference between mysqli and PDO in PHP?