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.phpfile and the users table from the PHP MySQL tutorial. - Use
mysqli_query()andmysqli_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:
| ID | Name | Mobile | |
|---|---|---|---|
| 3 | Pankit | 9898979797 | pankit@example.com |
| 2 | Sanjay | 9898969696 | sanjay@example.com |
| 1 | Ram | 9898989898 | ram@example.com |
How it works
ORDER BY id DESCsorts 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 thewhileloop 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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |