How can object-oriented programming principles be applied to improve database query handling in PHP?
Issue: Object-oriented programming principles can be applied to improve database query handling in PHP by creating classes for database connection, query execution, and result handling. This approach helps in encapsulating database-related functionality, promoting code reusability, and improving code organization.
// Database class for handling database connection
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'my_database';
private $conn;
public function __construct() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function close() {
$this->conn->close();
}
}
// Example usage
$db = new Database();
$result = $db->query("SELECT * FROM users");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . "<br>";
}
} else {
echo "0 results";
}
$db->close();