I have a PDO connection in my database class and recently I have been using this as an extension for other classes i.e. class Users extends Database this allows me to always keep a Database connection without having to have a function in my Users class.
However somebody pointed out that I shouldn't be doing this as its bad practice, why exactly is this bad practice? And how can I connect to my database class in my user class without extending?
Currently I have the call to the database inside my viewall() function I tried to put this in a __construct() function however it insisted on having parameters
I've tried the below code however I get the error message as follows:
Fatal error: Call to undefined method Database::prepare() in E:\xampp\htdocs\attendance\class.Register.php on line 13
Any ideas on how I can call on my database?
This is my code:
class.Connect.php
<?php // Database connection PDO class Database { public function __construct() { // Connection information $host = 'localhost'; $dbname = 'attendance'; $user = 'root'; $pass = ''; // Attempt DB connection try { $this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //echo 'Successfully connected to the database!'; } catch(PDOException $e) { echo $e->getMessage(); } } public function __destruct() { // Disconnect from DB $this->pdo = null; //echo 'Successfully disconnected from the database!'; } } ?> class.Register.php
<?php require 'class.Connect.php'; class Register { public function viewall() { $pdo = new Database(); $stmt = $pdo->prepare('SELECT * FROM users'); $stmt->execute(); $stmt->fetch(); } } $run = new Register(); $run->viewall(); ?>
Users instanceof Database? If something is not something else, it shouldn'textendit.extends DBTableor something, rather thanextends Database. But if you are trying to write your own ORM, you might want to stop for a moment and consider using one of the exising libraries available (eg Doctrine) that already do this (and have already solved all the problems you're going to encounter as you write this).