mysql 变量为空插入失败,将NULL变量插入数据库

I have variable set to NULL that im trying to insert into a database but for some reason they keep getting submitted as '0'. Im positive that column im trying to inset into allows NULL and that the default is set to to NULL. Heres my code:

$insert = NULL;

$query = mysql_query("INSERT INTO `table1` (column1) VALUES ('$insert')") or die(mysql_error());

解决方案Warning:

Please, don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi.

IF you want it to be NULL (and you really really still want to use mysqli_*) in the database you can do the following:

$insert = NULL;

$query = mysql_query("INSERT INTO `table1` (column1) VALUES ("

.(($insert===NULL)?

"NULL":

"'".mysql_real_escape_string($insert)."'").

")") or die(mysql_error());

But this could lead to nefarious SQL injection and is not recommended.

So: all in all you should be using prepared statements.

You can use MySQLi like so:

$dbHandle = new mysqli(...);

$query = "INSERT INTO `table1` (column1) VALUES (?)";

$statement = $dbHandle->prepare($query);

if($statement){

$statement->bind_param('s', $insert);

if(!$statement->execute()){

echo "Statement insert error: {$statement->error}";

}

$statement->close();

}

else {

echo "Insert error: {$dbHandle->error}";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值