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();
}
}
Related Questions
- How can variables be effectively used in SQL queries for inserting and updating data in PHP?
- What potential pitfalls should be considered when using file_exists() function in PHP to check for file existence?
- What are some alternative methods, such as using a profiler or writing proxy code, for monitoring method usage in PHP scripts across multiple servers?