This question already has an answer here:
This is the code I'm using to pass the database handle to my class:
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($db->connect_error)
die('MySQL connection error (' . $db->connect_errno . ') ' . $db->connect_error);
$linkgen = new Linkgen($db);
echo $linkgen->getLinksLeft();
And this is the code in the Linkgen
class:
class Linkgen {
private $db; // our database handle
private $linksLeft;
function __contruct($db)
{
$this->db = $db;
}
function getLinksleft()
{
$ip = $_SERVER['REMOTE_ADDR'];
$q = $this->db->prepare("SELECT links_left FROM `limits` WHERE ip=?");
$q->bind_param("s", $ip);
$q->execute();
$q->bind_result($this->linksLeft);
$q->fetch();
printf("%i links left", $this->linksLeft);
$q->close();
}
}
For some reason I get the non-object error when I call the getLinksLeft
method. I can't figure this out because from what I can see I'm referencing the database handle correctly.
Any help is appreciated, thanks.
Why not extend your object to become apart of mysqli?
And if you still want your error fixed then you have miss spelled
__construct
;)it is because your
$db
in theLinkgen
class is null or unset. You need to check it before you invokegetLinksleft()
.