【问题标题】:Insert NULL variable into database将 NULL 变量插入数据库
【发布时间】:2012-07-09 00:48:16
【问题描述】:

我将变量设置为 NULL,我试图将其插入数据库,但由于某种原因,它们一直被提交为“0”。我肯定我试图插入的列允许 NULL,并且默认设置为 NULL。这是我的代码:

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

【问题讨论】:

标签: php mysql null


【解决方案1】:

警告:

请不要将mysql_* 函数用于新代码。它们不再维护,社区已经开始deprecation process。相反,您应该了解prepared statements 并使用PDOMySQLi

IF 你希望它是NULL(你真的真的仍然想在你的数据库中使用mysqli_*)可以执行以下操作:

$insert = NULL;
$query = mysql_query("INSERT INTO `table1` (column1) VALUES ("
                         .(($insert===NULL)?
                                 "NULL":
                                 "'".mysql_real_escape_string($insert)."'").
                     ")") or die(mysql_error());

但这可能会导致恶意 SQL 注入,因此推荐。

Bobby Tables


所以:总而言之,您应该使用准备好的语句

你可以像这样使用MySQLi

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

【讨论】:

  • 我说的是第一个
  • @JonahKatz 你确定它在 mysql_* 行吗?
  • 您是否在某处某处缺少行尾的分号
  • -1 表示未修复第一个示例中的 SQL 注入漏洞。警告不是留下不安全代码的借口...
【解决方案2】:

试试这个静态查询:

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

使用变量:

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

【讨论】:

  • 这行得通,但我需要它是一个变量,因为有时变量不是空的
【解决方案3】:

尝试不带引号;

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

查询应该是;

插入table1 (column1) 值(NULL);

【讨论】:

  • You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '., '24')' at line 1
  • 它在我的服务器上工作...所以你一定是输入错误
猜你喜欢
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
相关资源
最近更新 更多