How can mysqli and pdo connections be effectively utilized in PHP for object-oriented programming with MySQL?
To effectively utilize mysqli and PDO connections in PHP for object-oriented programming with MySQL, it is important to create a separate class for database connections and handle all database operations within methods of this class. This approach helps in maintaining a clean and organized code structure, making it easier to manage database connections and queries.
// Database class for mysqli connection
class MysqliDatabase {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
return $this->connection->query($sql);
}
public function close() {
$this->connection->close();
}
}
// Database class for PDO connection
class PdoDatabase {
private $connection;
public function __construct($host, $username, $password, $database) {
$dsn = "mysql:host=$host;dbname=$database";
$this->connection = new PDO($dsn, $username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function query($sql) {
return $this->connection->query($sql);
}
public function close() {
$this->connection = null;
}
}