Is there a recommended best practice for handling database connections and queries in PHP classes, considering security and efficiency?
When handling database connections and queries in PHP classes, it is recommended to use prepared statements to prevent SQL injection attacks and ensure data security. Additionally, it is best practice to establish a separate database connection class to handle database connections and queries, promoting code reusability and maintainability.
<?php
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'mydatabase';
private $conn;
public function __construct() {
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function query($sql, $params = []) {
$stmt = $this->conn->prepare($sql);
$stmt->execute($params);
return $stmt;
}
}
?>
Related Questions
- What are some considerations to keep in mind when customizing window behavior in PHP?
- How can special characters like umlauts be properly displayed in PHP output, especially in the context of content management systems like Drupal?
- What potential issue is indicated by the error message "Failed opening 'install.php' for inclusion"?