View Full Version : Resolved MySQLi Prepared Statements

09-15-2009, 04:22 PM
I'm getting the following error:

Fatal error: Call to a member function bind_param() on a non-object in [edited out]security.php on line 86

My relevant code is:

$mysqli = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbSchema);
if (!mysqli_connect_errno()) {
$stmt = $mysqli->prepare("SELECT g.groupname FROM tblgroupmembers as gm LEFT JOIN tblusergroups as g ON (g.id = gm.groupid) WHERE (gm.user=?)");
$stmt->bind_param('s', $this->userName);

// do stuff with result

Specifically, the error is referring to this part (line 86):

$stmt->bind_param('s', $this->userName);

And stating that $stmt is a non-object, despite having been set above by:

$stmt = $mysqli->prepare("SELECT g.groupname FROM tblgroupmembers as gm LEFT JOIN tblusergroups as g ON (g.id = gm.groupid) WHERE (gm.user=?)");

I've run that query (with the "?" replaced with a single-quoted username) in MySQL Query Browser without error. However running the script with var_dump($stmt) right here (after the assignment of $stmt to the result of prepare()) shows $stmt to be a bool of value false.

So, prepare() is failing, returning false, and I'm trying to call a method of a Boolean variable. Bad. I get that. But what am I doing wrong with my prepare() call, as the SQL works in the Query Browser, and I've verified that mysqli_connect_errno() is false?

According to http://us.php.net/manual/en/mysqli.prepare.php:

$stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")
Should work...

09-15-2009, 04:43 PM
You will notice in the examples in the manual that the $stmt = $mysqli->prepare() is enclosed in an if() {} conditional test so that the remainder of the code that is dependent on $stmt is only executed when the prepare() is successful.

There is likely an error in the query statement. The query is parsed at the time of the prepare() statement. Use $mysqli->error to find out what error occurred -

09-15-2009, 04:47 PM
Sorry, I'm an idiot. Found my problem. Using the wrong schema on the database :(

CFMaBiSmAd, thanks for the response anyway, and yeah I had everything wrapped in IF checks, but removed that for debugging (an error is much nicer sometimes than a graceful failure.)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum