Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding "not null" in PDO?

Tags:

php

mysql

pdo

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?

like image 708
Hugo Zink Avatar asked Oct 09 '15 08:10

Hugo Zink


1 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();
like image 86
deceze Avatar answered Oct 14 '22 14:10

deceze