MySQL和PHP-插入NULL而不是空字符串
问题描述:
我有一条MySQL语句,该语句将一些变量插入数据库中.我最近添加了两个可选字段($ intLat,$ intLng).现在,如果未输入这些值,我将传递一个空字符串作为值.如何将明确的NULL值传递给MySQL(如果为空)?
I have a MySQL statement that inserts some variables into the database. I recently added 2 fields which are optional ($intLat, $intLng). Right now, if these values are not entered I pass along an empty string as a value. How do I pass an explicit NULL value to MySQL (if empty)?
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
'$intLat', '$intLng')";
mysql_query($query);
答
要将NULL传递给MySQL,您只需这样做.
To pass a NULL to MySQL, you do just that.
INSERT INTO table (field,field2) VALUES (NULL,3)
因此,在您的代码中,检查if $intLat, $intLng
是empty
,如果是,请使用NULL
而不是'$intLat'
或'$intLng'
.
So, in your code, check if $intLat, $intLng
are empty
, if they are, use NULL
instead of '$intLat'
or '$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)";