我的页面使用 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 是有值(value)的: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;在 MySqli 语句之前,插入的值是 NULL。
这是为什么呢? null 和 null 之间有什么区别?我跟着这个answer在 stackoverflow 中希望我可以轻松地插入 NULL,但随后出现了这个问题......
谢谢!
PS @stackoverflow 团队 - 你的拼写检查词典无法识别 stackoverflow 这个词!
最佳答案
您将 product_disc 准备为整数,null 不是整数。它被转换为 0。
虽然准备为字符串,肯定会解决您的问题,但它违背了准备 mysql 语句的目的。考虑这个解决方案:
mysqli_stmt_bind_param($stmt, $product_disc==null?'s':'i', $product_disc);
关于php - 使用 MySqli 向 MySql 记录插入 NULL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5677217/