[英]How to add a array variable parameter in mysql query?(PHP)
I need to do a query like: 我需要像这样的查询:
UPDATE screening
SET maileddate = NOW(),
reference = '{$reference[$user_id]}'
WHERE user_id IN(....)
And I want to do the judgement, when reference[$user_id] is empty, reference[$user_id] = NULL. 我想做一个判断,当reference [$ user_id]为空时,reference [$ user_id] = NULL。 My code is : 我的代码是:
if(empty($reference[$user_id]) || $reference[$user_id] == ''){
$reference[$user_id] = NULL;
}
But when I execute the query, if $reference[$user_id] is empty, the value of reference in database is empty but not null. 但是,当我执行查询时,如果$ reference [$ user_id]为空,则数据库中reference的值为空,但不为null。 What should I do to make it null? 我应该怎么做才能使其为空? thanks 谢谢
You may need to pass NULL
as a string to MySQL if the variable is empty. 如果变量为空,则可能需要将NULL
作为字符串传递给MySQL。 Use a different variable to hold the possibly NULL contents and quote the non-null contents. 使用其他变量来保存可能为NULL的内容并引用非null的内容。 Don't forget to escape it otherwise: 别忘了以其他方式转义它:
$refid = empty($reference['user_id']) ? "NULL" : "'" . mysql_real_escape_string($reference['user_id']) . "'";
UPDATE screening SET maileddate = NOW(), reference = '{$refid}'
WHERE user_id IN(....)
Just make it a string saying null. 只是将其设置为一个字符串,说为null。 If it's null $reference[$user_id] = 'null';
如果为空,则$reference[$user_id] = 'null';
Oh, also with the query you should be using reference IS null {$reference[$user_id]}
instead of the equals sign 哦,同样在查询中,您应该使用reference IS null {$reference[$user_id]}
而不是等号
Without seeing the rest of your code, my guess is it has something to do with reference = '{$reference[$user_id]}'
having {$reference[$user_id]}
in single quotes. 没有看到您的其余代码,我想这与reference = '{$reference[$user_id]}'
与单引号中的{$reference[$user_id]}
有关系。 MySQL is going to see whatever is in there as what should be in the database. MySQL将查看其中的内容以及数据库中的内容。 So if $reference[$user_id]
prints out as nothing (because it's NULL), that bit of your query will be reference = ''
rather than reference = NULL
. 因此,如果$reference[$user_id]
为空(因为它为NULL),则查询的那一部分将是reference = ''
而不是reference = NULL
。 You need to use the keyword NULL rather than the actual value NULL for the variable you use in the query. 您需要为查询中使用的变量使用关键字NULL而不是实际值NULL。
As an example: 举个例子:
$query = "UPDATE screening " .
"SET maileddate = NOW(), " .
"reference = " . ($reference[$user_id] === NULL ? 'NULL ' : "'{$reference[$user_id]}' ") .
"WHERE user_id IN(....)";
$reference = 'reference = ';
$reference .= ' empty($reference[$user_id]) ? 'NULL' : "'". mysql_real_escape_string($reference[$user_id]) . "'";
$query = "UPDATE screening
SET maileddate = NOW(),
$reference
WHERE user_id IN(....)";
Try this: 尝试这个:
$user_id = empty($reference[$user_id]) ? 'NULL' : $reference[$user_id];
$sql = "UPDATE screening
SET maileddate = NOW(),
reference = " . $user_id . "
WHERE user_id IN(....)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.