[英]Prevent empty array records from being submitted in to MYSQL database using php
I want to prevent the empty records in an array from being submitted to the MYSQL database: 我想防止将数组中的空记录提交到MYSQL数据库:
HTML part: HTML部分:
<input type="text" name="m_name[]" value="name"/>
<input type="text" name="m_lastname[]" value="lastname"/>
<input type="text" name="m_name[]" value="second_name"/>
<input type="text" name="m_lastname[]" value="second_lastname"/>
<input type="text" name="m_name[]" value=""/>
<input type="text" name="m_lastname[]" value=""/>
and this is the PHP and MySQL part: 这是PHP和MySQL的一部分:
if(!empty($_POST['m_name'])) $m_name = array_map('mysql_real_escape_string', $_POST['m_name']);
if(!empty($_POST['m_lastname'])) $m_lastname = array_map('mysql_real_escape_string', $_POST['m_lastname']);
for($l=0; $l < count($m_name); $l++){
mysql_query("INSERT INTO `group_members` SET
`m_name` ='".$m_name[$l]."',
`m_lastname` ='".$m_lastname[$l]."'"
);
}
The problem is that all the 6 inputs, whether those which does not include any values are being submitted to the database. 问题在于所有这6个输入(无论那些不包含任何值的输入)都将提交给数据库。 What am I doing wrong?!
我究竟做错了什么?!
我认为问题是,如果要使$m_name
不为空,但$m_lastname
为空,那么for循环将被执行,现场m_lastname
从表group_members
将插入后空。
Since nobody answered the question, I finally got how to do it and I will share it because somebody will encounter my problem and get in this question by chance: 由于没有人回答这个问题,所以我终于有了解决方法,我将分享它,因为有人会遇到我的问题并偶然遇到这个问题:
Simply use array_filter()
, which conveniently handles all this for you: 只需使用
array_filter()
,它可以为您方便地处理所有这些:
$m_name = array_filter(array_map('mysql_real_escape_string', $_POST['m_name']));
$m_lastname = array_filter(array_map('mysql_real_escape_string', $_POST['m_lastname']));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.