How can object-oriented programming principles be applied to improve database query functions in PHP?
To improve database query functions in PHP using object-oriented programming principles, we can create a Database class that encapsulates the connection to the database and query execution methods. This helps in better organization of code, reusability, and easier maintenance.
<?php
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) {
$result = $this->conn->query($sql);
return $result->fetch_all(MYSQLI_ASSOC);
}
public function close() {
$this->conn->close();
}
}
// Example usage
$db = new Database();
$results = $db->query("SELECT * FROM users");
print_r($results);
$db->close();
?>
Related Questions
- What are the potential pitfalls of not properly sanitizing user input before executing SQL queries in PHP?
- What are the potential pitfalls of not encoding characters correctly in PHP for database interactions?
- What are the advantages of using a single base template with extends in Smarty for managing content and navigation in PHP applications?