简体   繁体   中英

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:

HTML part:

<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:

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. 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:

$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']));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM