绑定“非空".在PDO中? [英] Binding "not null" in PDO?

查看:64
本文介绍了绑定“非空".在PDO中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现您可以在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);

这将成功地从数据库中提取所有foo,其中bar列为空.

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

但是,我现在想做相反的事情.我想获取bar列为 not null的所有列.

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

我知道我可以简单地将bar = :bar替换为bar 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.

这可能吗?

推荐答案

您不能绑定"NOT NULL".您只能绑定. "IS NOT NULL"不是值,它是完全不同的查询语法.您只需要动态地构建查询,值绑定就不能帮助您实现这一点:

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();

这篇关于绑定“非空".在PDO中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆