使用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
值。这就是我有问题的地方。我已确保将数据库表设置为;
允许空=是
默认-空
我处理表单提交的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服务器版本。。..
当我得到时;
[mac] => Array
(
[0] =>
[1] =>
[2] =>
)
如果我将PHP更改为insert中的以下内容(注意附加的
var_dump(mac)
),则查询将成功运行,但将' '
值插入数据库而不是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 ." )";
}
这有助于写出语法正确的查询所需的特定值