<?php
class UBC_DB
{
private $db;
public function connect()
{
$db = new mysqli('localhost', 'root', 'root', 'NewsTable');
}
public function getDB()
{
if(!$db)
{
printf("Can't connect to MySQL Server. ErrorCode: %s\n", mysqli_connect_error());
exit;
}
}
}
$api = new UBC_DB();
$api->connect();
$api->getDB();
?>
Hello, PHP masters.
I’ve got a problem here and need your help…
I’m trying to make a nice neat class to deal with DB connection… However,
even if that db is connected successfully and returns the appropriate result to $db, I cannot reuse this variable in another method in the same class! shouldn’t $db remember what it has received before? In getDB method, it says $db has nothing : ( PHP has a different variable scope-rules?
The scoping rules are different than other languages like Perl, it is true.
I suggest the following singelton-style DB class: