What potential pitfalls should be avoided when creating a MySQLi class in PHP?
One potential pitfall when creating a MySQLi class in PHP is not properly handling errors and exceptions that may occur during database operations. It is important to implement error handling to gracefully handle any issues that may arise, such as connection failures or query errors. By using try-catch blocks and checking for errors after each database operation, you can ensure that your application remains stable and secure.
class Database {
private $conn;
public function __construct($host, $username, $password, $database) {
$this->conn = new mysqli($host, $username, $password, $database);
if ($this->conn->connect_error) {
throw new Exception("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql) {
$result = $this->conn->query($sql);
if (!$result) {
throw new Exception("Query failed: " . $this->conn->error);
}
return $result;
}
}