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

How to Display MySQL Database Table Data in an HTML Table?

DDD
Release: 2024-12-19 04:29:09
Original
448 people have browsed it

How to Display MySQL Database Table Data in an HTML Table?

Showing Database Table Values in an HTML Table

In web development, it's common to retrieve data from a database and display it on a webpage in a tabular format. To accomplish this, we need to establish a connection to the database, execute queries to fetch the data, and then render it inside an HTML table.

Querying the Database

The first step is to establish a connection to the MySQL database using the mysqli_connect() function and run a query to retrieve the data using the mysqli_query() function. For example:

$con = mysqli_connect("localhost", "username", "password", "database_name");
$result = mysqli_query($con, "SELECT * FROM tickets");
Copy after login

Fetching and Iterating Through the Results

Once we have executed the query, we need to fetch the results and iterate through them to extract the individual values. We can use the mysqli_fetch_all() function to fetch all results in an associative array format:

$data = $result->fetch_all(MYSQLI_ASSOC);
Copy after login

Generating the HTML Table

Finally, we can create an HTML table using the

tag and populate it with the data. Each row of the table will represent a record from the database, with the field values appearing in the respective columns.

<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

By following these steps, you can easily retrieve data from a MySQL database and display it in an HTML table on a webpage.

The above is the detailed content of How to Display MySQL Database Table Data 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template