Insert empty value using Bindparam without error 不正确的整数值

Insert empty value using Bindparam without error Incorrect Integer value

我想使用 PDO 将一些数据插入到我的 MySql table 中。如果它不为空,它将具有 Integer 数据类型,所以我使用 PDO::PARAM_INT,但问题是不需要此数据,因此有时它是空的。

这让我出错:

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value.

那么我是否可以将这个空值变量传递到我的数据库中而不会在它具有空值时出错?这是我的代码片段:

$stmt = $db->prepare("INSERT INTO table (column) VALUES (:column)");
$stmt->bindParam(':column',$_POST['value'], PDO::PARAM_INT);
$stmt->execute();

一个空的 string 是不正确的 integer 值都是一样的。尽管过去是宽容的,但现在 MySQL 对类型的要求更加严格,默认情况下强制执行 STRICT MODE,因此不再接受整数字段的空字符串。

此外,PDO::PARAM_INT不会转换你的价值观。

因此,您必须手动投射它们

如果您想保留一个可能的 NULL 值,请像这样转换您的输入

$value = is_null($_POST['value']) ? null : (int)$_POST['value'];

如果你只想无条件地转换为整数,那就直接做吧

$value = (int)$_POST['value'];

这两个代码段都会将空字符串转换为 0,MySQL

很乐意接受它

在我的案例中,我是这样使用的:

if(empty($_POST['value'])){ $value = NULL; } else { $value = $_POST['value']; }
$stmt->bindParam(':column', $value);

它最适合我,从你这边试试 :-)