简体   繁体   中英

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. 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

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(....)";
$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(....)";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM