简体   繁体   English

使用MySqli将NULL值插入MySql记录

[英]Insert NULL values to MySql records using MySqli

My page sends using ajax data to a php script. 我的页面使用ajax数据发送到php脚本。 one of the vars that the script gets is: $product_disc now a small test that I have done inside the script clearly revealed that $product_disc is null. 脚本获得的其中一个变量是:$ product_disc现在我在脚本中完成的一个小测试清楚地显示$ product_disc为null。 the test: 考试:

if ($product_disc == null)
 {$test="null";}
 else {$test="not null";}

I make my code return $test to the ajax calling procedure: 我让我的代码返回$ test到ajax调用过程:

$return_array['success'] = array ('test' => $test);

And using Firebug I see that the ajax response has: "test":"null" 使用Firebug我看到ajax响应有:“test”:“null”
So i conclude that $product_disc is of value: null 所以我得出结论$ product_disc的值是:null

Now, inside my script I'm using the following code to insert data to MySql DB: 现在,在我的脚本中,我使用以下代码将数据插入MySql DB:

$stmt = mysqli_prepare($link, "INSERT INTO set_products (id,discount) VALUES (NULL , ?)");
mysqli_stmt_bind_param($stmt, "i", $product_disc);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

The query is being executed, but the value that was inserted is 0 and not NULL! 正在执行查询,但插入的值为0而不是NULL!
Only when I explicitly added: $product_disc=null; 只有当我明确添加:$ product_disc = null; before the MySqli statements, the value that was inserted was NULL. 在MySqli语句之前,插入的值为NULL。

Why is that? 这是为什么? What's the different between a null and a null? null和null之间有什么不同? I followed this answer in stackoverflow hoping that i could easily insert NULLs but then came this problem... 我在stackoverflow中遵循这个答案 ,希望我可以轻松地插入NULL,但后来出现了这个问题......

Thank you! 谢谢!

PS @stackoverflow team - Your spell checking dictionary doesn't recognize the word stackoverflow! PS @stackoverflow团队 - 您的拼写检查字典无法识别单词stackoverflow!

You prepare product_disc as integer, null is not an integer. 您将product_disc准备为整数,null不是整数。 It is converted to 0. 它被转换为0。

While preparing as a string, would definitely fix your issue, it defeats the purpose of preparing a mysql statement. 准备作为一个字符串,肯定会解决你的问题,它失败了准备一个mysql语句的目的。 Consider this solution: 考虑这个解决方案

mysqli_stmt_bind_param($stmt, $product_disc==null?'s':'i', $product_disc);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM