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

本文介绍了一种在使用PHP向数据库插入NULL值时遇到的问题及解决方案。主要讨论了如何正确地将NULL值写入数据库,避免被误转为'0'的情况,并提供了使用预处理语句来防止SQL注入的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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}";

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值