0

I'm learning MySQLi in php and I can't understand why I am getting an Call to a member function prepare() on a non-object error.

Here's my code as below:

public function fetch_posts($num = 5)
{

    global $mysqli;

    if($stmt = $mysqli->prepare("SELECT * FROM posts ORDER BY id desc LIMIT ?")) 
    {

       /* Bind parameters
          s - string, b - boolean, i - int, etc */
       $stmt -> bind_param("i", $num);

       /* Execute it */
       $stmt -> execute();

       /* Bind results */
       $stmt -> bind_result($result);

       /* Fetch the value */
       $stmt -> fetch();

       /* Close statement */
       $stmt -> close();

    }        
    $mysqli -> close();
}

$mysqli is the MySQLi connection call, $mysqli = new mysqli(DB_HOST, DB_ID, DB_PW, DB); which resides in the __construct() function, both which are within the same class.

Have I done something obviously wrong here? I can't see it.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • possible duplicate of [Call to a member function on a non-object](http://stackoverflow.com/questions/54566/), [Problem with Global Variables](http://stackoverflow.com/questions/923707/), [mysqli why does this happens?](http://stackoverflow.com/questions/725679/), [Why do I get this function call error on an non-object when I am calling a function on an object?](http://stackoverflow.com/questions/958038/). – outis Dec 23 '11 at 07:37

1 Answers1

0

$mysqli is not the MySQL connection for some reason.

If you don't have a debugger configured so you can step through the code, use gettype($mysqli) right before your prepare() call to see what it is you're dealing with.

Trott
  • 66,479
  • 23
  • 173
  • 212