Welche Alternativen gibt es, um die Vererbung der Datenbank in class.inc.php zu umgehen und die Property $db sinnvoller zu nutzen?
Um die Vererbung der Datenbank in class.inc.php zu umgehen und die Property $db sinnvoller zu nutzen, kann man die Datenbankverbindung direkt in der Klasse initialisieren. Dadurch wird die Abhängigkeit von der Vererbung entfernt und die Klasse wird eigenständiger.
class Database {
private $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
public function query($sql) {
$stmt = $this->db->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}
Keywords
Related Questions
- How can the issue of changing only the quantity of the last listed item in a shopping cart be resolved in PHP?
- What are the best practices for handling multiple checkbox values in PHP forms and storing them in a database?
- How can images be selected and included in a PDF document generated from form data in PHP using checkboxes?