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();
?>