What are the best practices for structuring a PHP database class to handle database interactions effectively?
When structuring a PHP database class to handle database interactions effectively, it is important to follow best practices such as using prepared statements to prevent SQL injection attacks, implementing error handling to gracefully handle database errors, and separating database connection details from the class itself for better flexibility and security.
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'my_database';
private $conn;
public function __construct() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql, $params = []) {
$stmt = $this->conn->prepare($sql);
if ($stmt === false) {
die("Error preparing statement: " . $this->conn->error);
}
if (!empty($params)) {
$stmt->bind_param(str_repeat('s', count($params)), ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$data = [];
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
$stmt->close();
return $data;
}
public function close() {
$this->conn->close();
}
}