How can PHP be used to retrieve data from a MySQL database and display it on a template file?
To retrieve data from a MySQL database and display it on a template file using PHP, you can use the MySQLi or PDO extension to establish a connection to the database, execute a query to fetch the data, and then loop through the results to display them on the template file.
<?php
// Establish a connection to the MySQL database
$connection = new mysqli('localhost', 'username', 'password', 'database_name');
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Execute a query to fetch data from a table
$query = "SELECT * FROM table_name";
$result = $connection->query($query);
// Loop through the results and display them on a template file
while ($row = $result->fetch_assoc()) {
echo "<p>" . $row['column_name'] . "</p>";
}
// Close the connection
$connection->close();
?>
Keywords
Related Questions
- What is the best practice for transferring $_SESSION data between different PHP files?
- Is it possible to define properties for classes using @property annotations in PHP, and how does this affect IDE functionality and code completion?
- What are the limitations or restrictions when using Whatsapp APIs for sending messages through PHP?