How can PHP output data from a database, as an array or formatted HTML?
To output data from a database in PHP, you can use SQL queries to retrieve the data and then format it as an array or HTML for display. You can fetch the data using functions like mysqli_fetch_array or mysqli_fetch_assoc to store the data in an array. To output the data as formatted HTML, you can loop through the array and echo out the data within HTML tags.
// Connect to the database
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
// Query to retrieve data from the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Fetch data as an array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Output data as formatted HTML
foreach($data as $row) {
echo '<div>';
echo '<p>Name: ' . $row['name'] . '</p>';
echo '<p>Email: ' . $row['email'] . '</p>';
echo '</div>';
}
// Close the connection
mysqli_close($connection);