MySQLとPHP-空の文字列ではなくNULLを挿入します


88

データベースにいくつかの変数を挿入するMySQLステートメントがあります。最近、オプションの2つのフィールド($ intLat、$ intLng)を追加しました。現在、これらの値が入力されていない場合は、空の文字列を値として渡します。明示的なNULL値をMySQLに渡すにはどうすればよいですか(空の場合)?

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  '$intLat', '$intLng')";
mysql_query($query);

回答:


143

NULLをMySQLに渡すには、それを実行します。

INSERT INTO table (field,field2) VALUES (NULL,3)

だから、あなたのコードでは、チェックがif $intLat, $intLngありempty、彼らがしている場合は、使用するNULL代わりに、'$intLat'または'$intLng'

$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  $intLat, $intLng)";

9
This doesn't add a mysql NULL value. This set the attribute to the string "NULL" which is different from the mysql NULL value. I'm just saying that you wrote two different things, first is correct the second not so much I think.
G4bri3l

23
@G4bri3l: In the $query string, $intLat and $intLng are not quoted. So, when the variables are interpolated, it will be , NULL, NULL);.
Rocket Hazmat

2
Oh yeah I see that now. Nice! Thanks for taking the time to point it out to me ;)
G4bri3l

@G4bri3l: No prob. I'm here to help :)
Rocket Hazmat

3
@alessadro: This question is very old. If you are concatenating variables into a SQL query like that, then you are doing it wrong! Please switch to using prepared statements in either PDO or MySQLi.
Rocket Hazmat

17

If you don't pass values, you'll get nulls for defaults.

But you can just pass the word NULL without quotes.


8
He'll only get NULL for default, if the table is set up that way.
Rocket Hazmat

2
To me that's what "optional" means.
dkretz


13

All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db


No need for quotes around the "NULL".
Louis

4

Normally, you add regular values to mySQL, from PHP like this:

function addValues($val1, $val2) {
    db_open(); // just some code ot open the DB 
    $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES ('$val1', '$val2')";
    $result = mysql_query($query);
    db_close(); // just some code to close the DB
}

When your values are empty/null ($val1=="" or $val1==NULL), and you want NULL to be added to SQL and not 0 or empty string, to the following:

function addValues($val1, $val2) {
    db_open(); // just some code ot open the DB 
    $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
        (($val1=='')?"NULL":("'".$val1."'")) . ", ".
        (($val2=='')?"NULL":("'".$val2."'")) . 
        ")";
    $result = mysql_query($query);
    db_close(); // just some code to close the DB
}

Note that null must be added as "NULL" and not as "'NULL'" . The non-null values must be added as "'".$val1."'", etc.

Hope this helps, I just had to use this for some hardware data loggers, some of them collecting temperature and radiation, others only radiation. For those without the temperature sensor I needed NULL and not 0, for obvious reasons ( 0 is an accepted temperature value also).


For column defined integers, the other solution it works fine, but for text fields, I had to break up the query as above into a string concatenation, like radhoo did above. $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (". "NULL". ", ".$val2.")";
Brian

2

your query can go as follows:

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
      VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$lng', '" . ($lat == '')?NULL:$lat . "', '" . ($long == '')?NULL:$long . "')";
mysql_query($query);

2
$intLat, and $intLng are the optional ones.
Rocket Hazmat

This will not work. There are quite a few things wrong with this code snippet (apart from using the wrong variables, as Rocket pointed out). Because of the precedence of the ternary operator, you'll need parentheses around the expression. But crucially, you are still surrounding the column value in single quotes, so you are back to square one, assigning a string, not a database NULL. Also, you are using PHPs NULL (unquoted) keyword, which evaluates to an empty string in a string context, so again, you are assigning an empty string.
MrWhite

1

Check the variables before building the query, if they are empty, change them to the string NULL


1

you can do it for example with

UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'

1

For some reason, radhoo's solution wouldn't work for me. When I used the following expression:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')?"NULL":("'".$val1."'")) . ", ".
    (($val2=='')?"NULL":("'".$val2."'")) . 
    ")";

'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')? :("'".$val1."'")) . ", ".
    (($val2=='')? :("'".$val2."'")) . 
    ")";

The blank resulted in the correct null (unquoted) being inserted into the query.

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.