Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi prepared statement returning false

I'm trying to run multiple queries on my database using MySQLi. This is my code:

$stmt = $mysqli->prepare('SELECT password FROM `users` WHERE username=? LIMIT 1');
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($hashedPass);
$stmt->fetch();

/* Check the passwords match */
$pwdHasher = new PasswordHash(8, FALSE);
if(!$pwdHasher->CheckPassword($password, $hashedPass))
    exit;

$stmt = $mysqli->prepare('SELECT u_id FROM `users` WHERE username=? LIMIT 1');
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($u_id);
$stmt->fetch();

But when the code is run I get this error:

Fatal error: Call to a member function bind_param() on a non-object in C:\wamp\www\ajax\login.php on line 42

I have checked that the database fields exist, so it's not that. The first query works, it just seems to be the second one that doesn't. I've run the query on its own in phpMyAdmin and that successfully produces a result set, so I really don't know what's wrong.

like image 956
James Dawson Avatar asked Jan 02 '12 14:01

James Dawson


People also ask

What is MySQLi-> Prepare?

mysqli::prepare -- mysqli_prepare — Prepares an SQL statement for execution.

What is Prepare() in php?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?").

How to use prepared statement in MySQL?

A prepared statement in MySQL represents a precompiled statement. A statement is compiled and stored in a prepared statement and you can later execute this multiple times. Instead of values we pass place holders to this statement. If you want to execute several identical queries (that differ by values only).

When to use prepared statement?

If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead. The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created.


1 Answers

prepare returns false if an error occurs. try

$stmt = $mysqli->prepare('SELECT u_id FROM `users` WHERE username=? LIMIT 1');
if ($stmt === FALSE) {
    die ("Mysql Error: " . $mysqli->error);
}

and some mysql error should be displayed.

like image 152
user823255 Avatar answered Oct 28 '22 11:10

user823255