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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With