Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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];
    }
}
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];
  }
}
$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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top