What are some common pitfalls when developing a database class in PHP, especially in terms of error handling and variable naming?
One common pitfall when developing a database class in PHP is not properly handling errors. It is important to catch and handle exceptions to prevent the script from crashing and to provide meaningful error messages for debugging. Another common issue is inconsistent variable naming, which can lead to confusion and errors in the code. It is best practice to use descriptive and consistent variable names to improve code readability and maintainability.
// Example of proper error handling in a database class
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
try {
$this->connection = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
}
// Example of proper variable naming in a database query method
public function query($sql, $params = []) {
$statement = $this->connection->prepare($sql);
$statement->execute($params);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}