How can object-oriented principles be effectively applied to database access in PHP using mysqli?
To effectively apply object-oriented principles to database access in PHP using mysqli, you can create a class that encapsulates database connection logic and methods for executing queries. This allows for better organization, reusability, and maintainability of database-related code.
<?php
class Database {
private $conn;
public function __construct($host, $username, $password, $dbname) {
$this->conn = new mysqli($host, $username, $password, $dbname);
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 of using the Database class
$db = new Database("localhost", "username", "password", "database_name");
$result = $db->query("SELECT * FROM table_name");
while ($row = $result->fetch_assoc()) {
// Process each row
}
$db->close();
?>
Keywords
Related Questions
- What are the considerations for handling file permissions in PHP when dealing with LAMP systems?
- How can PHP be used to populate dropdown options from a database query and handle user input selections?
- Are there specific recommendations for handling date comparisons and outputs in PHP applications, especially when dealing with date pickers?