What are some best practices for displaying data in a table using PHP?
When displaying data in a table using PHP, it is important to ensure that the table is well-structured and easy to read. One best practice is to separate the HTML markup from the PHP logic by using a template system like PHP's `echo` function. Another best practice is to use CSS to style the table for better visual presentation. Additionally, make sure to properly escape any user input to prevent security vulnerabilities such as SQL injection.
<?php
// Sample data to display in the table
$data = [
['Name' => 'John Doe', 'Age' => 30, 'Email' => 'john.doe@example.com'],
['Name' => 'Jane Smith', 'Age' => 25, 'Email' => 'jane.smith@example.com'],
['Name' => 'Alice Johnson', 'Age' => 35, 'Email' => 'alice.johnson@example.com']
];
// Start the table
echo '<table>';
// Display table header
echo '<tr><th>Name</th><th>Age</th><th>Email</th></tr>';
// Display table rows with data
foreach ($data as $row) {
echo '<tr>';
echo '<td>' . htmlspecialchars($row['Name']) . '</td>';
echo '<td>' . $row['Age'] . '</td>';
echo '<td>' . htmlspecialchars($row['Email']) . '</td>';
echo '</tr>';
}
// End the table
echo '</table>';
?>
Related Questions
- What are some recommended resources or tutorials for beginners to improve their understanding of PHP syntax and database interactions?
- What are common pitfalls when using arrays for navigation in PHP?
- Are there any browser extensions or plugins that facilitate PHP development, such as Xdebug helper or FirePHP, and how effective are they in enhancing the development process?