MySQL 和 PHP - 插入 NULL 而不是空字符串 [英] MySQL and PHP - insert NULL rather than empty string
本文介绍了MySQL 和 PHP - 插入 NULL 而不是空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 MySQL 语句,可以将一些变量插入到数据库中.我最近添加了 2 个可选字段($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)";
这篇关于MySQL 和 PHP - 插入 NULL 而不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文