Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO checking field against prepared :param, handling IS NULL conditions [closed]

I have the following query:

//query:
$query = "
    SELECT field1 FROM table 
    WHERE 
        field2 = :PARAM1
    AND ...
    AND fieldx = :PARAM1X";

//params:
$params = array();
$params [":PARAM" . $i] = NULL;

//prepare and execute:
$o = $cnx->prepare($query);
$o->execute($params);

How could I bind the params with NULL values? Will PDO change the = :PARAM1 to IS NULL automatically? To make it clear, trying to compute WHERE field = null doesn't work in mysql and will never return anything. We must use WHERE field IS NULL instead.

That's what I'm dealing with now.

I must say that my first tests are positive but I don't really want to discover a side effect in 6 months in a production environment...

like image 257
Sebas Avatar asked Sep 28 '12 01:09

Sebas


2 Answers

As comment from PHP Docs says,

bindValue(':PARAM1', null, PDO::PARAM_INT);

or

$myNull = null;
$stmt->bindParam(':PARAM1', $myNull, PDO::PARAM_NULL);
like image 139
John Woo Avatar answered Oct 24 '22 04:10

John Woo


if you want to bind params will null values then you need to use bindValues

bindValue(':param', null, PDO::PARAM_INT);

so for your query it can be something like this.

$sth = $dbh->prepare('SELECT field1 FROM table WHERE field2 = :PARAM1 AND fieldx = :PARAM1X');
$sth->bindValue(':PARAM1', null, PDO::PARAM_INT);

hope this helps.

like image 32
Ibrahim Azhar Armar Avatar answered Oct 24 '22 04:10

Ibrahim Azhar Armar