【问题标题】:How to insert NULL Value in PHP [duplicate]如何在 PHP 中插入 NULL 值
【发布时间】:2014-05-19 09:13:27
【问题描述】:

我想在数据库中插入 NULL 值

$managerId = $_POST['managerId'];

if($managerId == 0)
{
    $managerId = NULL;
}
else
{
    $managerId = 14;
}
$mysql_user_resultset = mysqli_query($con, "INSERT into user (managerId) VALUES ('$managerId')");

我是这样使用的。它不工作,值不插入。

如何在同一变量中同时插入 Null 值和某个值..

因为 '$managerId' - 单引号。

如何定义这两种类型

【问题讨论】:

  • 在表格结构中添加一个空规则。
  • 如何添加。规则是什么
  • 使用准备好的语句。
  • 您绝对应该为此使用准备好的语句。

标签: php mysql


【解决方案1】:

当你连接 $managerId 变量时,你会得到这个查询字符串:

"INSERT into user (managerId) VALUES ('')"

所以,您正在尝试插入一个空字符串。这不是你想要的。最简单的方法是删除引号,例如

"INSERT into user (managerId) VALUES ($managerId)"

如果您的 managerId 字段可以为 null,并且对于整数值仍然有效,这将起作用。

【讨论】:

  • (string) NULL == "",而不是"null"
  • 您可以使用 is_string 来检查值是否为字符串,并将引号添加到变量中。
  • 感谢 cbuckley,我显然很困惑。我编辑了答案。
【解决方案2】:
  1. 将列默认值设置为 NULL
  2. 试试这条线:

    $managerId = (int) $managerId; // Convert to INT to avoid SQL injection $mysql_user_resultset = mysqli_query($con, "INSERT into user (managerId) VALUES (".($managerId?$managerId:'DEFAULT').")");

如果设置了$managerId,则插入$managerId,否则默认值为NULL。

【讨论】:

    【解决方案3】:

    PHP 将空值连接为空字符串。所以,要让它工作,试试这个:

    if($managerId == 0)
    {
        $managerIdInQuery = 'NULL';
    }
    else
    {
        $managerIdInQuery = 14;
    }
    $mysql_user_resultset = mysqli_query($con, "INSERT into user (managerId) VALUES ($managerIdInQuery)");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-28
      • 2021-08-11
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多