简体   繁体   English

如何检查 $_POST 中的可选字段

[英]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.虽然这会导致无休止的 if 语句......即使使用三元语法它仍然很混乱。 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. array_merge()将合并这些值,使后面的值覆盖前面的值。

If you don't want to trust array_merge() then you can do a foreach() loop.如果你不想信任array_merge()那么你可以做一个foreach()循环。

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

remember to sanitize your $_POST values!记得清理你的 $_POST 值!

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):编辑:如果您希望将可选的 $_POST 值与表中可能存在或不存在的字段相匹配,您可以执行以下操作(我假设您正在使用 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.编辑:使用 Owen 的代码,它更简洁,我的是同一件事的更详细的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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