views:

42

answers:

1

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.

A: 

Why not extend your object to become apart of mysqli?

class Linkgen extends mysqli
{
    private $_linksLeft;

    function __construct()
    {
        parent::__construct(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    }

   function getLinksleft()
   {
        $ip = $_SERVER['REMOTE_ADDR'];
        $q = $this->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();
    }
    //...
}

//Usage:
$Linkgen = new Linkgen();
echo $Linkgen->getLinksLeft();

And if you still want your error fixed then you have miss spelled __construct ;)

RobertPitt