using nulls in a mysqli prepared statement

Posted on

using nulls in a mysqli prepared statement – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and mysql . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about using nulls in a mysqli prepared statement.

In a mysqli prepared statement, a NULL gets turned into ” (in the case of a string) or 0 (in the case of an integer). I would like to store it as a true NULL. Is there any way of doing this?

Solution :

It’s possible to bind a true NULL value to the prepared statements (read this).

You can, in fact, use mysqli_bind_parameter to pass a NULL value to the database. simply create a variable and store the NULL value (see the manpage for it) to the variable and bind that. Works great for me anyway.

Thus it’ll have to be something like:

<?php
    $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

    // person is some object you have defined earlier
    $name = $person->name();
    $age = $person->age();
    $nickname = ($person->nickname() != '') ? $person->nickname() : NULL;

    // prepare the statement
    $stmt = $mysqli->prepare("INSERT INTO Name, Age, Nickname VALUES (?, ?, ?)");

    $stmt->bind_param('sis', $name, $age, $nickname);
?>

This should insert a NULL value into the database.

For anyone coming looking at this because they are having problems binding NULL in their WHERE statement, the solution is this:

There is a mysql NULL safe operator that must be used:

<=>

Example:

<?php
$price = NULL; // NOTE: no quotes - using php NULL
$stmt = $mysqli->prepare("SELECT id FROM product WHERE price <=> ?"); // Will select products where the price is null
$stmt->bind_param($price);
?>

The comments to the PHP documentation on mysqli_stmt::bind_param indicate that passing in NULL was not easily possible.


Please see @creatio’s answer: https://stackoverflow.com/a/6892491/18771


Solutions offered in the comments do some pre-preparation work on the prepared statement, replacing the "?" markers with "NULL" for every param that has the PHP null value. The modified query string is then used.

The following function is from user comment 80119:

function preparse_prepared($sQuery, &$saParams)
{
    $nPos = 0;

    $sRetval = $sQuery;
    foreach ($saParams as $x_Key => $Param)
    {
        //if we find no more ?'s we're done then
        if (($nPos = strpos($sQuery, '?', $nPos + 1)) === false)
        {
            break;
        }

        //this test must be done second, because we need to 
        //increment offsets of $nPos for each ?.
        //we have no need to parse anything that isn't NULL.
        if (!is_null($Param))
        {
            continue;
        }


        //null value, replace this ? with NULL.
        $sRetval = substr_replace($sRetval, 'NULL', $nPos, 1);

        //unset this element now
        unset($saParams[$x_Key]);
    }
    return $sRetval;
} 

(It’s not really the coding style I would have done it in, but if it works…)

I store all parameters in an array and pass them in bind_param function using array_shift($myArray). NULL is accepted like that.

<?php
$mysqli=new mysqli('localhost','root','','test');
$mysqli->query("CREATE TABLE test_NULL (id int(11))");
if($query=$mysqli->prepare("insert into test_NULL VALUES(?)")){
    $query->bind_param('i',$null); //note that $null is undefined
    $query->execute();
}else{
    echo __LINE__.' '.$mysqli->error;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *