What is the best practice for creating a dynamic table in PHP with data from MySQL?
When creating a dynamic table in PHP with data from MySQL, the best practice is to fetch the data from the database using SQL queries, loop through the results, and dynamically generate the table rows and columns using HTML. This allows for flexibility in displaying different datasets without hardcoding the table structure.
<?php
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Fetch data from MySQL database
$sql = "SELECT * FROM table_name";
$result = mysqli_query($connection, $sql);
// Create dynamic table
echo "<table>";
echo "<tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row['column1']."</td><td>".$row['column2']."</td><td>".$row['column3']."</td></tr>";
}
echo "</table>";
// Close connection
mysqli_close($connection);
?>
Related questions
-
SQL injection Cross-site scripting (XSS) htmlentities
-
postcodes PHP database proximity searches
-
DateTime date strtotime