What function is used in the PHP script to output SQL query results in table form?
To output SQL query results in table form in a PHP script, you can use the "mysqli_fetch_assoc" function to fetch each row as an associative array, and then loop through the results to generate an HTML table. You can use keys of the associative array as table headers and values as table data. Here is a complete PHP code snippet that demonstrates how to output SQL query results in table form:
<?php
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Perform a query
$sql = "SELECT * FROM your_table";
$result = mysqli_query($connection, $sql);
// Output data in table form
echo "<table border='1'>";
echo "<tr>";
while ($row = mysqli_fetch_assoc($result)) {
if (empty($headers)) {
$headers = array_keys($row);
foreach ($headers as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
// Close connection
mysqli_close($connection);
?>
Keywords
Related Questions
- What is the difference between using isset() and empty() in PHP to check for empty values in an array?
- What are some best practices for handling restricted HTML tags when integrating PHP scripts into a website?
- How can a beginner programmer approach writing a function to search for multiple words in an array in PHP?