Is it advisable to mix object-oriented and procedural programming in PHP when handling database connections?
It is generally advisable to use object-oriented programming for handling database connections in PHP as it provides better structure, reusability, and maintainability. Mixing object-oriented and procedural programming can lead to code complexity and inconsistency. It is recommended to stick to one programming paradigm for better code organization and readability.
// Object-oriented approach for handling database connections
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'my_database';
public $connection;
public function __construct() {
$this->connection = new mysqli($this->host, $this->username, $this->password, $this->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();
}
}
// Example usage
$database = new Database();
$result = $database->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo $row['username'] . "<br>";
}
$database->close();