I have a MySQLi class that I am using but when I initliaze it and then try and perform a query, I get the following error:
Notice: Undefined variable: MySQLi in ...
Im new to mysqli and classes
Here is my Class:
<?PHP
class DB
{
private static $instance;
private $MySQLi;
private function __construct(array $dbOpt)
{
$this->MySQLi = @ new MySQLi($dbOpt['db_host'],$dbOpt['db_user'],$dbOpt['db_pass'],$dbOpt['db_name']);
if(mysqli_connect_errno()) {
throw new Exception("Database connection error");
}
$this->MySQLi->set_charset("utf8");
}
public static function init(array $dbOpt)
{
if(self::$instance instanceof self) {
return false;
} else {
self::$instance = new self($dbOpt);
}
}
public static function getMySQLiObj() {
return self::$instance->$MySQLi;
}
public static function query($q) {
/* This is the line that fails */
return self::$instance->$MySQLi->query($q);
}
public static function escape($str) {
return self::$instance->$MySQLi->real_escape_string(htmlspecialchars($str));
}
}
?>
Here is my query:
//Connect to database
DB::init($dbOpt);
$result = DB::query("SELECT * FROM myTable");
if(!$result) {
echo "MySQLi Query failed";
}
else {
//handle query
}
I have commented above the line that fails.
Remove the $
. The code of your DB::query()
method should look like this:
return self::$instance->MySQLi->query($q);
Note, a static var will be accsessed this way:
Classname::$varname
an instance var will be accessed as follows:
$instance = new Classname();
$instance->varname;
You don't need the $ on the ->$MySQLi in that line.
$ is only needed on variables outside classes. You have this error on several other lines in the code as well.