1

参数 $isConfirmed 的值可以是 null、0 或 1。当我尝试发送“null”时,PDO 正在返回一个异常。我该如何解决这个问题?

$dbHandler = $dbConnection->prepare("INSERT INTO `Group` (visitId, guideId, groupSize, isConfirmed) VALUES (:visitId, :guideId, :groupSize, :isConfirmed)");
        for($i = 0; $i < count($groupId); $i++) { 
                $dbHandler->bindParam(":visitId", $visitId, PDO::PARAM_INT); 
                $dbHandler->bindParam(":guideId", $guideId, PDO::PARAM_INT); 
                $dbHandler->bindParam(":groupSize", $groupSize, PDO::PARAM_INT); 
                $dbHandler->bindParam(":isConfirmed", $isConfirmed, PDO::PARAM_INT); 
                $dbHandler->execute(); 
        }
4

2 回答 2

2

更新
好吧,我是个傻瓜,我所有的光顾。

实际上不需要弄乱参数类型。如果值为 NULL,PDO 会自动绑定 NULL:

$sql = "CREATE TEMPORARY TABLE `nulltest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NULL DEFAULT '',
  PRIMARY KEY (`id`)
)";

$pdo->exec($sql);

$stm = $pdo->prepare("INSERT INTO nulltest SET name = ?");
foreach (array("foo", null) as $val)
{
    $stm->execute([$val]);
}
$stm->bindParam(1, $val, PDO::PARAM_STR);
$stm->execute();

$stm->bindValue(1, NULL, PDO::PARAM_INT);
$stm->execute();

$sql = "SELECT count(*) FROM nulltest WHERE name IS NULL";
$num = $pdo->query($sql)->fetchColumn();
var_dump($num); // outputs 3

所以,正确的代码是

$sql = "INSERT INTO `Group` (visitId, guideId, groupSize, isConfirmed) 
        VALUES (:visitId, :guideId, :groupSize, :isConfirmed)";
$stm = $dbConnection->prepare($sql);
$stm->bindParam(":visitId",     $visitId,     PDO::PARAM_INT); 
$stm->bindParam(":guideId",     $guideId,     PDO::PARAM_INT); 
$stm->bindParam(":groupSize",   $groupSize,   PDO::PARAM_INT); 
$stm->bindParam(":isConfirmed", $isConfirmed, PDO::PARAM_INT); 

foreach($groupId as $void)
{ 
    $stm->execute(); 
}

空值将被写入。

于 2013-10-21T14:19:16.163 回答
1

改变 :

$dbHandler->bindParam(":isConfirmed", $isConfirmed, PDO::PARAM_INT); 

至 :

if(is_null($isConfirmed) || !is_int($isConfirmed)){
 $v=null;
 $dbHandler->bindParam(":isConfirmed", $v, PDO::PARAM_NULL);
}else{
 $dbHandler->bindParam(":isConfirmed", $isConfirmed, PDO::PARAM_INT);
}
于 2013-10-21T14:08:20.700 回答