I have two classes :
SQL Connection Class
class MysqlDB {
protected $_mysql;
protected $_where = array();
protected $_query;
protected $_paramTypeList;
public function __construct($host, $username, $password, $db) {
$this->_mysql = new mysqli($host, $username, $password, $db) or die('There was a problem connecting to the database');
}
public function query($query)
{
//...................... }
public function __destruct() {
$this->_mysql->close();
}
}
User Class
class cUser {
private $_name;
private $_email;
private $_password;
public function __construct() {
$this->_name = '';
$this->_email = '';
$this->_password = '';
}
public function getUser($username) {
global $db;
return $db->query("SELECT * FROM user where username='$username'");
}
}
**index.php**
<?php
require_once('cMysqlDB.php');
require_once('cUser.php');
$db = new MysqlDB('host','username','password','db');
$user = new cUser();
$userData = $user->getUser('username');
print_r($userData);
?>
Totally works! Thanks to Sabeen Malik
Though I am not entirely sure why you are inheriting the
Usersfrom theMySQLclass. But anyway, if you really need to do it that way.Instead of
do:
You don’t need the
$this->_connjust use$this->_mysqlI believe the
MysqlDBclass would be in the singleton pattern. The User class would just use the methods of the MySQLDB class by talking to its object like :$results = MySQLDB::instance()->query(whatever);or something on those lines. Some people even use a global
$dbobject and use that in their classes ( i am not condoning that though ) but there are several ways to go about this. I am not sure if you have chosen the right one.Edit:
Using the global $db, you can get the user data like this: