I am trying to make the switch from procedural PHP to OO PHP.
I have created a Db class that looks like this:
class Db {
protected static $connection;
/*
Attempt to connect to database.
@Return bool false on failure, mysqli object instance on success
*/
public function connect() {
if(!isset(self::$connection)) {
//Parse DB info from configuration file
$config = parse_ini_file('../validconfigpath/config.ini');
//Attempt to connect to the datbase
self::$connection = new mysqli($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbname']);
if(self::$connection === false) {
//Database connection unsuccessful, how to handle?
echo "Error connecting to database.<br />";
return false;
}
return self::$connection;
}
}
/*
* Query the database
* @param $query The sql string
* @return mixed The result of the mysqli::query() function
*/
public function query($query) {
//Connect to the database
$connection = $this -> connect();
//Query the database
$result = $connection -> query($query);
return $result;
}
/*
* Fetch rows from the database (SELECT query)
* @param $query The query string
* @return bool false on failure / array Database rows on success
*
*/
public function select($query) {
$rows = array();
$result = $this -> query($query);
if ($result === false) {
return false;
}
while($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
/*
* Fetch last inserted ID from the database
* @return ID of last inserted record using this connection, or 0 if no INSERT or UPDATE statements were sent
*/
public function inserted_id() {
$connection = $this -> connect();
return $connection -> insert_id;
}
public function quote($value) {
$connection = $this -> connect();
return "'" . $connection -> real_escape_string($value) . "'";
}
}
I am trying to test the quote
function, by using this code:
include_once 'Classes/DB.php';
$db = new Db();
$firstName = $db -> quote("First");
echo $firstName. "<br />";
$lastName = $db -> quote("Last");
echo $lastName. "<br />";
I get my expected output for $firstName
like so:
'First'
But for my second output for $lastName
I get:
Fatal error: Uncaught Error: Call to a member function real_escape_string() on null in ..\Classes\DB.php:91 Stack trace: #0 ..\index.php(11): Db->quote('Last') #1 {main} thrown in ..\Classes\DB.php on line 91
As best I can tell something is happening to $connection
but I can't figure out what is wrong with connect()
.
Also I got to thinking is it best to just create a connection in __construct
?