I followed the OOP in this article Using PHP with MySQL - the right way
Seems ok until I start using the placeholder variable for the object:
php > require('class_lib.php');
php > $test = new Db();
I'm using interactive PHP as it seems easier to test the code line by line. This line seems to be the problem:
php > $result = $test->query("SELECT * FROM test");
PHP Fatal error: Call to a member function query() on a non-object in class_lib.php on line 23
This is the OOP code:
<?php
class Db {
protected static $connection;
public function connect(){
if (!isset(self::$connection)){
$configfile = realpath("database.ini");
echo $configfile . PHP_EOL;
$config = parse_ini_file($configfile);
$connection = mysqli_connect($config['host'],$config['user'],$config['password'],$config['dbname'],$config['port']);
}
if (self::$connection === false){
die ("Database connection failed.");
return mysql_errno(self::$connection);
}
return self::$connection;
}
public function query($query){
$connection = $this->connect();
$result = $connection->query($query);
return $result;
}
public function select_rows($query){
$rows = array();
$result = $this->query($query);
if ($result === false){
return false;
}
while ($result = $result->fetch_assoc()){
$rows[] = $row;
}
return $rows;
}
public function error(){
$connection = $this->connect();
return $connection->error;
}
public function quote($value){
$connection = $this->connect();
return "'" . $connection->real_escape_string($value) . "'";
}
}
I am also reading Classes and Objects and was hoping for some insight to help me absorb the knowledge a little faster so I can resume the more general aspects of the project.
I have not a clue what the error means. I'm following the basic ideas of OOP in PHP.
Thank you.