【发布时间】:2019-03-15 06:27:33
【问题描述】:
使用 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]:语法错误或访问冲突:1064 你有一个 SQL 语法错误;检查与您对应的手册 正确语法的 MySQL 服务器版本.. ..
当我var_dump(mac) 我得到;
[mac] => Array
(
[0] =>
[1] =>
[2] =>
)
如果我在插入中将 PHP 更改为以下(注意附加的 ' '),则查询运行成功,但而不是 null 值,empty 值被插入数据库。
$arr_mac = $_POST['mac'] ;
for ($i = 0; $i < count($arr_mac); $i++) {
$sql = "INSERT INTO staff (mac) VALUES (' ".$arr_mac[$i]." ')
}
感谢任何建议。
【问题讨论】:
-
你能分享完整的生成查询吗?
-
我认为你必须从字面上插入
NULL,如果值为空:$sql = "INSERT INTO staff (mac) VALUES (" . ($arr_mac[$i] ? "'{$arr_mac[$i]}'" : 'NULL') . ")
标签: php html mysql arrays mariadb