In what scenarios would object-oriented programming (OOP) be beneficial for handling SQL queries in PHP?
Object-oriented programming (OOP) can be beneficial for handling SQL queries in PHP when you want to encapsulate the database connection logic, query execution, and result processing into reusable and modular classes. This approach can help improve code organization, readability, and maintainability by separating concerns and promoting code reusability.
<?php
// Define a Database class to encapsulate database connection logic
class Database {
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 fetchArray($result) {
return $result->fetch_assoc();
}
// Add more methods as needed
}
// Example usage
$database = new Database("localhost", "username", "password", "dbname");
$result = $database->query("SELECT * FROM users");
while ($row = $database->fetchArray($result)) {
echo $row['username'] . "<br>";
}
?>