使用MySql为MySql记录插入NULL值


Insert NULL values to MySql records using MySqli

我的页面使用ajax发送数据到php脚本。脚本获取的变量之一是:$product_disc现在,我在脚本中做了一个小测试,清楚地显示$product_disc为空。测试:

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

我让我的代码返回$test到ajax调用过程:

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

和使用Firebug,我看到ajax响应有:" test":"null"
因此,我得出结论,$product_disc的值为:null

现在,在我的脚本中,我使用以下代码向MySql数据库插入数据:

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

正在执行查询,但是插入的值是0而不是NULL!
只有当我明确地添加:$product_disc=null;在mysql语句之前,插入的值是NULL。

为什么?null和null有什么区别?我在stackoverflow中遵循这个答案,希望我可以轻松插入null,但随后出现了这个问题…

谢谢!

PS @stackoverflow团队-你的拼写检查字典不识别单词stackoverflow!

您准备product_disc为整数,null不是整数。它被转换为0。

虽然准备作为字符串,肯定会解决你的问题,它违背了准备mysql语句的目的。考虑这个解决方案:

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