简体   繁体   English

PHP mysql PDO 拒绝设置 NULL 值

[英]PHP mysql PDO refuses to set NULL value

I am unable to set a nullable field with a default value of null to null using mysql pdo.我无法使用 mysql pdo 将默认值为 null 的可空字段设置为 null。 I can do it using straight sql.我可以使用直接的 sql 来完成。

I have tried: (mostly from this question How do I insert NULL values using PDO? )我试过:(主要来自这个问题How do I insert NULL values using PDO?

  1. Null Int空整数

    bindValue(':param', null, PDO::PARAM_INT);
  2. Null Null空空

    bindValue(':param', null, PDO::PARAM_NULL);
  3. 'Null', Int '空',整数

    bindValue(':param', 'NULL', PDO::PARAM_INT);
  4. 'Null', Null '空',空

    bindValue(':param', 'NULL', PDO::PARAM_NULL);
  5. Null空值

    bindValue(':param', null);
  6. 'Null' '空值'

     bindValue(':param', 'NULL');
  7. and the bindParam counterparts of 5 and 6 with a variable that held the value of the binding.和 5 和 6 的bindParam对应物,带有一个保存绑定值的变量。

Everything from PDO results in the value being set to 0. PDO 中的所有内容都会将该值设置为 0。

PHP Version: PHP 5.3.2-1ubuntu4.10 PHP 版本: PHP 5.3.2-1ubuntu4.10

MYSQL SERVER VERSION: 5.1.63-0ubuntu0.10.04.1 MYSQL 服务器版本: 5.1.63-0ubuntu0.10.04.1

EDIT Screenshot of column info编辑列信息的屏幕截图

图片

The following works for me:以下对我有用:

<?php

$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "pass");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$stmt = $pdo->prepare("INSERT INTO `null_test` (`can_be_null`) VALUES (:null)");
$stmt->bindValue(":null", null, PDO::PARAM_NULL);

$stmt->execute();

Pass in PHP's null , with type of PDO::PARAM_NULL . PDO::PARAM_NULL PHP 的null ,类型为PDO::PARAM_NULL Also, make sure your prepare emulation is set to false.此外,请确保您的准备模拟设置为 false。 That might help.那可能会有所帮助。

I will strong recommend to first assign all parameters to variables and then pass those variables to the bindParam() method.我强烈建议首先将所有参数分配给变量,然后将这些变量传递给bindParam()方法。

You can assign by passing NULL to those variables and it will work fine.您可以通过将 NULL 传递给这些变量来分配,它会正常工作。

$myVar = NULL;
$conn->bindParam(':param1' , $myVar , PDO::PARAM_STR);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM