简体   繁体   中英

How to check for optional fields in $_POST

At the moment my code looks like this:

# Assign values for saving to the db
$data = array(
    'table_of_contents' => $_POST['table_of_contents'],
    'length' => $_POST['length']
);

# Check for fields that may not be set
if ( isset($_POST['lossless_copy']) )
{
   $data = array(
       'lossless_copy' => $_POST['lossless_copy']
    );
}

// etc.

This would lead to endless if statements though... Even with the ternary syntax it's still messy. Is there a better way?

How about this:

// this is an array of default values for the fields that could be in the POST
$defaultValues = array(
    'table_of_contents' => '',
    'length' => 25,
    'lossless_copy' => false,
);
$data = array_merge($defaultValues, $_POST);
// $data is now the post with all the keys set

array_merge() will merge the values, having the later values override the previous ones.

If you don't want to trust array_merge() then you can do a foreach() loop.

foreach ($_POST as $key => $value) {
  $data[$key] = $value;
}

remember to sanitize your $_POST values!

edit : if you're looking to match up optional $_POST values with fields that may or may not exist in your table, you could do something like this (i'm assuming you're using mysql):

$fields = array();
$table  = 'Current_Table';

// we are not using mysql_list_fields() as it is deprecated
$query  = "SHOW COLUMNS from {$table}";
$result = mysql_query($query);
while ($get = mysql_fetch_object($result) ) {
  $fields[] = $get->Field;
}

foreach($fields as $field) {
  if (isset($_POST[$field]) ) {
    $data[$field] = $_POST[$field];
  }
}

You could build an array of optional fields:

$optional = array('lossless_copy', 'bossless_floppy', 'foo');
foreach ($optional as $field) {
    if (isset($_POST[$field])) {
        $data[$field] = $_POST[$field];
    }
}
$formfields = $_POST;
$data = array();
foreach(array_keys($formfields) as $fieldname){
  $data[$fieldname] = $_POST[$fieldname];
}

This will add all fields that are returned including submit. If you need to know if a checkbox has not been checked, you're going to have to use code like you posted. If you only care about checkboxes that are checked, you can use the above code.

This would probably not work for multiple formfields using the same name, like radio buttons.

EDIT: Use Owen's code, it's cleaner, mine is a more verbose version of the same thing.

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