PHP的空值不等于MySQL的空值吗? [英] Isn't PHP's null value equal to MySQL's null value?

查看:236
本文介绍了PHP的空值不等于MySQL的空值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php上有一个变量,有时它可以是NULL,我想将此变量插入到我的数据库中.但是问题是,PHP的空值不会作为空值插入db.

I have a variable on php and it sometimes can be NULL and I want to insert this variable to my db. But problem is, PHP's null value does not insert to db as null value.

我在db上的列允许使用空值.

My column on db allows null values.

if($variable != true){
   $variable = null;
}

//insert my null value to db

$insert = $db->prepare("insert into mytable set mycolumn = $variable" );
$insert->execute();

//mycolumn is an integer column which is DEFAULT null

//above query fails. Why?

推荐答案

这是因为在创建查询字符串时,PHP null会转换为空字符串".

That is because PHP null is converted into the empty string "" when you create the query string.

$variable = null;
$insert = "insert into mytable set mycolumn = $variable" ;
echo $insert;

会产生:

insert into mytable set mycolumn = 

要修复您的查询,您需要检查PHP变量是否为null并将其更改为字符串NULL. (现在也在@MarkB的评论中提到.)

To fix your query you would need to check if the PHP variable is null and change it to string NULL. (Also now mentioned in the comment of @MarkB.)

if ($variable == null){
    $variable = "NULL";
}

这将产生:

"insert into mytable set mycolumn = NULL"

请注意,由于NULL现在已连接到另一个字符串,因此NULL周围没有.

*(注意:insert into tablename set ..是不正确的,您是insert数据还是update tablename set数据.)

*(note: insert into tablename set .. is not correct, you either insert data or you update tablename set data.)

这篇关于PHP的空值不等于MySQL的空值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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