开发者

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]}'
                     W开发者_JS百科HERE user_id IN(....)

And I want to do the judgement, when reference[$user_id] is empty, 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. 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. Use a different variable to hold the possibly NULL contents and quote the non-null contents. 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. If it's 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 = '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(....)";


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. MySQL is going to see whatever is in there as what should be in the database. 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. You need to use the keyword NULL rather than the actual value NULL for the variable you use in the query.

As an example:

$query = "UPDATE screening " . 
             "SET maileddate = NOW(), " . 
                 "reference = " . ($reference[$user_id] === NULL ? 'NULL ' : "'{$reference[$user_id]}' ") . 
                 "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(....)";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜