tags:

views:

1009

answers:

4

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?

+3  A: 
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];
  }
}
Owen
This won't help with any fields that are not set in the POST.
Darryl Hein
+4  A: 

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];
    }
}
ojrac
He will still end up with an array without certain keys set. They should instead be set to defaults.
Darryl Hein
Good point. If that's a concern, you can always add something like "else { $data[$field] = false; }" - or whatever you want for a default.
ojrac
A: 
$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.

+9  A: 

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.

Darryl Hein
Good general solution when you need explicit defaults. +1
ojrac
Excellent solution, making use of built in functions.
dcousineau