使用 PHP 版本 7.1.9,MariaDB 10.1.26。
我正在向 MySQL 数据库提交一组表单数据。该表单允许添加动态输入,当添加动态输入时,它们看起来像这样;
// I have removed additional html form code for brevity
<input type="text" name="mac[]">
<input type="text" name="mac[]">
<input type="text" name="mac[]">
etc...
有时这些输入会是空的,这是允许的。当输入为空时,我想将一个 NULL
值插入到我的数据库中。这是我遇到问题的地方。
我已确保我的数据库表设置为;
- 允许 null = 是
- 默认 - 空
我处理表单提交的 PHP 代码如下(请忽略任何安全漏洞,这是简化的代码);
// I have removed additional php code for brevity
$arr_mac = $_POST['mac'] ? "'".$_POST['mac']."'" : 'NULL';
for ($i = 0; $i < count($arr_mac); $i++) {
$sql = "INSERT INTO staff (mac) VALUES ( ".$arr_mac[$i]." )
}
我收到的错误是;
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax.. ..
当我 var_dump(mac)
我得到;
[mac] => Array
(
[0] =>
[1] =>
[2] =>
)
如果我在插入中将 PHP 更改为以下内容(注意附加的 ' '
),查询将成功运行,但 而不是 null
值,空
值被插入到数据库中。
$arr_mac = $_POST['mac'] ;
for ($i = 0; $i < count($arr_mac); $i++) {
$sql = "INSERT INTO staff (mac) VALUES (' ".$arr_mac[$i]." ')
}
如有任何建议,我们将不胜感激。
最佳答案
我假设您使用错误的语法构建查询。使用给定的代码,您的 INSERT
可能如下所示:
INSERT INTO staff (mac) VALUES ()
您的代码未正确处理 NULL
情况 - 将变量设置为 NULL
不会导致使用文字 NULL
进行构建查询。
这可能有帮助:
$arr_mac = $_POST['mac'] ? "'".$_POST['mac']."'" : 'NULL';
for ($i = 0; $i < count($arr_mac); $i++) {
$value = $arr_mac[$i];
if(!$value) {
$value = 'NULL';
} else {
$value = your_favorite_escaping_algorithm($value);
}
$sql = "INSERT INTO staff (mac) VALUES ( ". $value ." )";
}
这有助于写出语法正确查询所需的特定 NULL
值
关于php - 为动态输入数组插入空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52738597/