What are some best practices for integrating MySQL database queries with Smarty templates in PHP to efficiently display data?
When integrating MySQL database queries with Smarty templates in PHP, it is important to separate the logic of querying the database from the presentation layer. This can be achieved by creating a PHP file that handles the database queries and passes the retrieved data to the Smarty template for display. By following this approach, you can ensure a clean separation of concerns and improve the efficiency of displaying data on the front end.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query the database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$conn->close();
// Pass data to Smarty template
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display('template.tpl');
?>
Keywords
Related Questions
- In what situations is it recommended to sort arrays directly in a SQL query rather than in PHP code?
- What security considerations should be taken into account when allowing users to view and interact with profiles in a PHP-based forum or website?
- How can the menu be modified to stay open when a new gallery is selected?