Jump to content

How to use prepared statement ? for IS NULL


tork
Go to solution Solved by requinix,

Recommended Posts

Here's what works:

 

$q = "SELECT user_id FROM users WHERE pass=? AND active IS NULL";

$r = mysqli_prepare($dbc, $q)

mysqli_stmt_bind_param($r, 's', $pw);  

 

mysqli_stmt_execute($r);

 

 

However, what I'd like to do is make the SELECT like the following to check active IS NULL:

 

$a = 'IS NULL';

 

$q = "SELECT user_id FROM users WHERE pass=? AND active=?";

$r = mysqli_prepare($dbc, $q)

mysqli_stmt_bind_param($r, 'ss', $pw, $a);  

 

mysqli_stmt_execute($r);

 

 

Since this doesn't work, anybody got any ideas what would work?

 

Link to comment
Share on other sites

  • Solution

You can't: prepared statements are about passing data and IS NULL is actually about changing the structure of the query itself. "IS" is an operator like > and = and you can't change operators after you've prepared the statement.

 

PHP doesn't have a good solution for passing an arbitrary number of parameters to bind_param(), but you can still do it.

$q = "SELECT user_id FROM users WHERE";
$bind = array("");

// password
$q .= " pass = ?";
$bind[0] .= "s";
$bind[] =& $pw; // reference

// active
if ($a === null) {
	$q .= " AND active IS NULL";
} else {
	$q .= " AND active = ?";
	$bind[0] .= "s";
	$bind[] =& $a; // reference
}

$r = mysqli_prepare($dbc, $q);
call_user_func_array(array($r, "bind_param"), $bind); // easier to call it as a method

mysqli_stmt_execute($r);
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.