使用 PDO 插入 NULL 而不是空字符串

编程入门 行业动态 更新时间:2024-10-28 04:16:40
本文介绍了使用 PDO 插入 NULL 而不是空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个表,它有一些可以为空的字段,当用户在 HTML 表单字段中不输入任何内容时,我想在该字段中插入 NULL,而不是一个空字符串(这很重要,因为我稍后会在这些表上进行一些 SELECT)使用 WHERE x IS NOT NULL 等条件.

I have a table which has some nullable fields and when the user enters nothing into the HTML form field, I want to insert NULL into that field, not an empty string (this is important as some of my SELECTs on these tables later use conditions such as WHERE x IS NOT NULL).

但是,这个版本的 bindParam 代码在可空字段中插入了一个空字符串而不是 NULL.

However, this version of bindParam code inserts an empty string into the nullable field instead of NULL.

$stmt2->bindParam(':title', $title, PDO::PARAM_STR);

我读了很多书,发现这是在字段中插入 null 的答案:

I've been reading quite a bit and figured out that this is the answer to insert null into the field instead:

$stmt2->bindParam(':title', $title, PDO::PARAM_NULL);

但这意味着我需要预先检查所有传递给可空字段的参数以确定它们是否为空,如果是,则传递 PDO::PARAM_NULL 而不是 PDO::PARAM_STR.我当然可以这样做,但希望可能有一个设置,它会告诉 PDO 如果遇到空字符串,请插入 null.

But this means I need to pre-check all parameters that are being passed to nullable fields to determine if they are empty, and if so pass the PDO::PARAM_NULL instead of PDO::PARAM_STR. I can of course do this, but was hoping there might be a setting which would just tell PDO if it encounters an empty string, insert null instead.

我偶然发现了这个

$this->dbh->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);

但它没有影响,随着进一步研究,我认为这只会影响出路的记录,而不是入路的记录.

But it has no effect and with further research I'm thinking this only affects record on the way out, not on the way in.

除了预先检查变量之外还有其他选择吗?

Any options other than pre-checking the variables?

推荐答案

如果你想要 null,只需插入 null 而不是空字符串.

If you want null, just insert null instead of empty string.

$stmt2->bindParam(':title', $title === '' ? null : $title, PDO::PARAM_STR);

更多推荐

使用 PDO 插入 NULL 而不是空字符串

本文发布于:2023-11-05 19:50:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561686.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   空字符串   PDO   NULL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!