gpt4 book ai didi

php - MySQL 和 PHP - 插入 NULL 而不是空字符串

转载 作者:IT老高 更新时间:2023-10-28 11:57:03 30 4
gpt4 key购买 nike

我有一个 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);

最佳答案

要将 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)";

关于php - MySQL 和 PHP - 插入 NULL 而不是空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4620391/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com