开发者

how to only insert the filled text inputs?

开发者 https://www.devze.com 2022-12-14 04:43 出处:网络
this is my code: <input type=\"text\" name=\"text[]\" /> <input type=\"text\" name=\"text[]\" />

this is my code:

<input type="text" name="text[]" />

<input type="text" name="text[]" />

<input type="text" name="text[]" />

if (!empty($_POST['text'])) {
foreach ($_POST['text'] AS $value) {
    // add to the database
    $sql = 'INSERT INTO tableName SET fieldName 开发者_开发技巧= "' . mysql_real_escape_string($value) . '"';
}

}

I want this to only insert the fields that are filled, for example if the first two inputs are filled, insert those and skip the last one which is empty.


You're already using empty() to check $_POST you can also use it to check $value

if (!empty($_POST['text'])) {
foreach ($_POST['text'] AS $value) {
    // add to the database
    if (!empty($value))
      $sql = 'INSERT INTO tableName SET fieldName = "' . mysql_real_escape_string($value) . '"';
}


The most brain-dead way to solve the problem would be to check the string length of each element in the text array.

foreach( $_POST['text'] as $value ) {
    if( !empty( $value ){
        // add to the database
        $sql = 'INSERT INTO tableName SET fieldName = "' . mysql_real_escape_string($value) . '"';
    }
}

However, I would seriously consider switching to a framework that does some sort of form validation. I hear good things about cakePHP and CodeIgniter, and they may be worth checking out.

0

精彩评论

暂无评论...
验证码 换一张
取 消