php5 class with mysqli connection
Posted: Sat Apr 11, 2009 5:43 am
Hi
I have started learning php5 and I have hit an annoying problem which i just cant understand I am sure its simple but after googling for the last couple of days i still havent found the answer.
The thing is I want one class which connects to the db and all my other classes use that class to connect to the db.
What I have is:
and my test class I am trying to get to call and use the db class is:
But i get the "Call to undefined method DB::query()" which is true because my db has no query function, think I am going at this the wrong way, just want a db connection i can use in all my classes.
I have started learning php5 and I have hit an annoying problem which i just cant understand I am sure its simple but after googling for the last couple of days i still havent found the answer.
The thing is I want one class which connects to the db and all my other classes use that class to connect to the db.
What I have is:
Code: Select all
class DB {
private $connection;
private static $_instance;
private function __construct() {
$this->connection = new mysqli('localhost', 'user', 'pass','database');
}
public static function get_connection() {
if(is_null(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
}
and my test class I am trying to get to call and use the db class is:
Code: Select all
class mine {
private static $mysqli;
public function __construct () {
self::$mysqli = DB::get_connection();
}
public function test(){
$sql = "SELECT * FROM table";
$result = self::$mysqli->query($sql);
while ($test = self::$mysqli->fetch_assoc($result)) {
echo $test['email'] . "<br />";
}
}
}