Home » Php » php – Binding "not null" in PDO?

php – Binding "not null" in PDO?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I recently found out that you can bind null values in PDO:

$stmt = $db->prepare('SELECT * FROM foo WHERE bar = :bar');
$stmt->execute(array(':bar'=>null));
$foo = $stmt->fetchAll(PDO::FETCH_OBJ);

This would successfully fetch all foo from the database, where the bar column is null.

However, I would now like to do the opposite. I would like to fetch all columns where the bar column is not null.

I am aware I could simply replace bar = :bar with bar IS NOT NULL. However, I would like to avoid that, and instead do it through prepared statements, because I sometimes have to build the query string dynamically and having to do it manually would be a lot of extra work.

Is this possible?

How to&Answers:

You cannot bind “NOT NULL”. You can only bind values. “IS NOT NULL” is not a value, it’s completely different query syntax. You will simply have to dynamically build your query, value binding cannot help you with that:

$query = 'SELECT ... WHERE ';
if (/* condition is NOT NULL */) {
    $query .= 'foo IS NOT NULL';
    $stmt = $db->prepare($query);
} else {
    $query .= 'foo = :foo';
    $stmt = $db->prepare($query);
    $stmt->bindValue('foo', $foo);
}
$stmt->execute();

Answer:

I am afraid you are wrong with your assumption. Although you can bind NULL values in general, WHERE bar = NULL statement won’t return you any rows, neither with raw SQL or PDO. This whole statement will be evaluated to NULL and won’t match any row.

Instead, you can use a NULL-safe equal to operator, <=>, to match fields that are either NULL or have some value. But to have values that are not null, you still have to have another query.