How can the connection to a database be effectively managed in PHP when using Smarty for templating?
When using Smarty for templating in PHP, it is important to manage the connection to the database effectively to ensure optimal performance and security. One way to achieve this is by creating a separate database class that handles the connection and query execution, which can be included in the Smarty templates when needed.
// Create a separate database class
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
return $this->connection->query($sql);
}
public function close() {
$this->connection->close();
}
}
// Usage in Smarty template
$db = new Database('localhost', 'username', 'password', 'database');
// Example query execution
$result = $db->query("SELECT * FROM table_name");
// Close the database connection
$db->close();