Home > Backend Development > PHP Tutorial > How to Display MySQL Database Values in an HTML Table?

How to Display MySQL Database Values in an HTML Table?

Mary-Kate Olsen
Release: 2024-12-28 13:33:10
Original
514 people have browsed it

How to Display MySQL Database Values in an HTML Table?

Displaying MySQL Database Values in an HTML Table on a Webpage

To retrieve and display values from a database table in an HTML table, follow these steps:

Get the Data:

  1. Establish a connection to the database using mysqli_connect.
  2. Execute a query to fetch the desired data using mysqli_query.
  3. Convert the query result into an associative array using fetch_all.

Example:

$con = mysqli_connect("localhost", "peter", "abc123", "my_db");
$result = mysqli_query($con, "SELECT * FROM tickets LIMIT 50");
$data = $result->fetch_all(MYSQLI_ASSOC);
Copy after login

Display the Data:

  1. Create an HTML table and set the border attribute for visibility.
  2. Use a PHP loop to iterate through the $data array, creating table rows and columns for each record.

Example:

<table border="1">
    <tr>
        <th>Submission ID</th>
        <th>Form ID</th>
        <th>IP</th>
        <th>Name</th>
        <th>E-mail</th>
        <th>Message</th>
    </tr>
    <?php foreach($data as $row): ?>
    <tr>
        <td><?= htmlspecialchars($row['submission_id']) ?></td>
        <td><?= htmlspecialchars($row['formID']) ?></td>
        <td><?= htmlspecialchars($row['IP']) ?></td>
        <td><?= htmlspecialchars($row['name']) ?></td>
        <td><?= htmlspecialchars($row['email']) ?></td>
        <td><?= htmlspecialchars($row['message']) ?></td>
    </tr>
    <?php endforeach ?>
</table>
Copy after login

This code will generate an HTML table with the data from the "tickets" table, displaying the values in the corresponding columns.

The above is the detailed content of How to Display MySQL Database Values in an HTML Table?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template