Home >Backend Development >PHP Tutorial >How can I display MySQL database table data as an HTML table?
Displaying MySQL Database Table Values in an HTML Table
This query aims to retrieve data from a MySQL database table and present it as an HTML table on a webpage. The provided database has a table named tickets with fields such as submission_id, formID, IP, name, email, and message. This query demonstrates how to retrieve and display this data.
To achieve this, the code employs a two-step approach: data retrieval followed by table rendering.
Data Retrieval
$con = mysqli_connect("localhost","peter","abc123","my_db"); $result = mysqli_query($con,"SELECT * FROM tickets"); $data = $result->fetch_all(MYSQLI_ASSOC);
This section initializes a MySQL connection and issues a query to fetch all rows from the tickets table. The query result is stored in the $result variable. Then, the fetch_all() method is called to retrieve all query rows as an array within the $data variable. This array associates field names with their corresponding values.
Table Rendering
<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>
This section renders an HTML table with columns corresponding to the field names. It uses a foreach loop to iterate through each row in the $data array. For each row, it creates a table row, populating each cell with the corresponding field value. The htmlspecialchars() function is employed to prevent cross-site scripting attacks by encoding special characters in the data.
By combining data retrieval and table rendering, this code enables you to retrieve and display MySQL database table values within an HTML table on a webpage.
The above is the detailed content of How can I display MySQL database table data as an HTML table?. For more information, please follow other related articles on the PHP Chinese website!