php 如何使用 PDO 插入 NULL 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1391777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I insert NULL values using PDO?
提问by Nacho
I'm using this code and I'm beyond frustration:
我正在使用此代码,我感到非常沮丧:
try {
$dbh = new PDO('mysql:dbname=' . DB . ';host=' . HOST, USER, PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
}
catch(PDOException $e)
{
...
}
$stmt = $dbh->prepare('INSERT INTO table(v1, v2, ...) VALUES(:v1, :v2, ...)');
$stmt->bindParam(':v1', PDO::PARAM_NULL); // --> Here's the problem
PDO::PARAM_NULL, null, '',all of them fail and throw this error:
PDO::PARAM_NULL, null, '',他们都失败并抛出这个错误:
Fatal error: Cannot pass parameter 2 by reference in /opt/...
致命错误:无法通过 /opt/... 中的引用传递参数 2
回答by JasonWoof
I'm just learning PDO, but I think you need to use bindValue, not bindParam
我只是在学习 PDO,但我认为你需要使用bindValue,而不是bindParam
bindParamtakes a variable, to reference, and doesn't pull in a value at the time of calling bindParam. I found this in a comment on the php docs:
bindParam需要一个变量来引用,并且在调用bindParam. 我在 php 文档的评论中发现了这一点:
bindValue(':param', null, PDO::PARAM_INT);
EDIT: P.S. You may be tempted to do this bindValue(':param', null, PDO::PARAM_NULL);but it did not work for everybody (thank you Will Shaver for reporting.)
编辑:PS 您可能很想这样做,bindValue(':param', null, PDO::PARAM_NULL);但它并不适合所有人(感谢 Will Shaver 的报告。)
回答by Joe Phillips
When using bindParam()you must pass in a variable, not a constant. So before that line you need to create a variable and set it to null
使用bindParam()时必须传入一个变量,而不是一个常量。因此,在该行之前,您需要创建一个变量并将其设置为null
$myNull = null;
$stmt->bindParam(':v1', $myNull, PDO::PARAM_NULL);
You would get the same error message if you tried:
如果您尝试过,您会收到相同的错误消息:
$stmt->bindParam(':v1', 5, PDO::PARAM_NULL);
回答by ChrisF
When using INTEGERcolumns (that can be NULL) in MySQL, PDO has some (to me) unexpected behaviour.
在 MySQL 中使用INTEGER列(可以是NULL)时,PDO 有一些(对我而言)意外的行为。
If you use $stmt->execute(Array), you have to specify the literal NULLand cannot give NULLby variable reference.
So this won't work:
如果使用$stmt->execute(Array),则必须指定文字NULL并且不能通过NULL变量引用给出。所以这行不通:
// $val is sometimes null, but sometimes an integer
$stmt->execute(array(
':param' => $val
));
// will cause the error 'incorrect integer value' when $val == null
But this will work:
但这会起作用:
// $val again is sometimes null, but sometimes an integer
$stmt->execute(array(
':param' => isset($val) ? $val : null
));
// no errors, inserts NULL when $val == null, inserts the integer otherwise
Tried this on MySQL 5.5.15 with PHP 5.4.1
在 MySQL 5.5.15 和 PHP 5.4.1 上试过这个
回答by Pedro Guglielmo
For those who still have problems (Cannot pass parameter 2 by reference), define a variable with null value, not just pass null to PDO:
对于还有问题的人(Cannot pass parameter 2 by reference),定义一个空值的变量,而不是直接传null给PDO:
bindValue(':param', $n = null, PDO::PARAM_INT);
Hope this helps.
希望这可以帮助。
回答by user1719210
I had the same problem and I found this solution working with bindParam :
我遇到了同样的问题,我发现这个解决方案与 bindParam 一起工作:
bindParam(':param', $myvar = NULL, PDO::PARAM_INT);
回答by Arian Acosta
If you want to insert NULLonly when the valueis emptyor '', but insert the valuewhen it is available.
如果你想插入NULL只有当value是empty或'',但插入value时,它是可用的。
A) Receives the form data using POST method, and calls function insert with those values.
A) 使用 POST 方法接收表单数据,并使用这些值调用函数插入。
insert( $_POST['productId'], // Will be set to NULL if empty
$_POST['productName'] ); // Will be to NULL if empty
B) Evaluates if a field was not filled up by the user, and inserts NULLif that's the case.
B) 评估用户是否未填写字段,NULL如果是这种情况,则插入。
public function insert( $productId, $productName )
{
$sql = "INSERT INTO products ( productId, productName )
VALUES ( :productId, :productName )";
//IMPORTANT: Repace $db with your PDO instance
$query = $db->prepare($sql);
//Works with INT, FLOAT, ETC.
$query->bindValue(':productId', !empty($productId) ? $productId : NULL, PDO::PARAM_INT);
//Works with strings.
$query->bindValue(':productName',!empty($productName) ? $productName : NULL, PDO::PARAM_STR);
$query->execute();
}
For instance, if the user doesn't input anything on the productNamefield of the form, then $productNamewill be SETbut EMPTY. So, you need check if it is empty(), and if it is, then insert NULL.
例如,如果用户没有productName在表单的字段上输入任何内容,那么$productName将会是SETbut EMPTY。因此,您需要检查它是否是empty(),如果是,则插入NULL。
Tested on PHP 5.5.17
在 PHP 5.5.17 上测试
Good luck,
祝你好运,
回答by hector teran
Try This.
尝试这个。
$stmt->bindValue(':v1', null, PDO::PARAM_NULL); // --> insert null
回答by Vincent
Based on the other answers but with a little more clarity on how to actually use this solution.
基于其他答案,但对如何实际使用此解决方案有更清晰的了解。
If for example you have an empty string for a time value but you want to save it as a null:
例如,如果您有一个时间值的空字符串,但您想将其保存为空值:
if($endtime == ""){
$db->bind(":endtime",$endtime=NULL,PDO::PARAM_STR);
}else{
$db->bind("endtime",$endtime);
}
Notice that for time values you would use PARAM_STR, as times are stored as strings.
请注意,对于时间值,您将使用 PARAM_STR,因为时间存储为字符串。
回答by centurian
In my case I am using:
就我而言,我使用的是:
SQLite,
prepared statements with placeholders to handle unknown number of fields,
AJAX request sent by user where everythingis a string and there is no such thing like
NULLvalue andI desperately need to insert
NULLs as that does not violates foreign key constrains(acceptable value).
SQLite,
带有占位符的准备好的语句来处理未知数量的字段,
用户发送的 AJAX 请求,其中所有内容都是字符串,没有
NULL值和我迫切需要插入
NULLs 因为这不会违反外键约束(可接受的值)。
Suppose, now user sends with post: $_POST[field1]with value value1which can be the empty string ""or "null"or "NULL".
假设,现在用户用后发送:$_POST[field1]用值value1可以是空字符串""或"null"或"NULL"。
First I make the statement:
首先我声明:
$stmt = $this->dbh->prepare("INSERT INTO $table ({$sColumns}) VALUES ({$sValues})");
where {$sColumns}is sth like field1, field2, ...and {$sValues}are my placeholders ?, ?, ....
这里{$sColumns}是某事像field1, field2, ...和{$sValues}是我的占位符?, ?, ...。
Then, I collect my $_POSTdata related with the column names in an array $valuesandreplace with NULLs:
然后,我收集$_POST与数组中列名相关的数据$values并替换为NULLs:
for($i = 0; $i < \count($values); $i++)
if((\strtolower($values[$i]) == 'null') || ($values[$i] == ''))
$values[$i] = null;
Now, I can execute:
现在,我可以执行:
$stmt->execute($values);
and among other bypass foreign key constrains.
以及其他绕过外键约束。
If on the other hand, an empty string does makes more sense then you have to check if that field is part of a foreign key or not (more complicated).
另一方面,如果空字符串确实更有意义,那么您必须检查该字段是否是外键的一部分(更复杂)。

