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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Will
  • 10,731
  • 6
  • 22
  • 16

2 Answers2

3

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
  • 56,863
  • 21
  • 114
  • 161
0

it is because your $db in the Linkgen class is null or unset. You need to check it before you invoke getLinksleft().

apaderno
  • 28,547
  • 16
  • 75
  • 90
antanse
  • 11
  • 2
  • 1
    This question is over 2 years old, and was already successfully answered and accepted. Try focusing your efforts on new questions! – Madara's Ghost Nov 15 '12 at 19:36