code_junkie

How to check for optional fields in $_POST

Nov 11th, 2011
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. # Assign values for saving to the db
  2. $data = array(
  3. 'table_of_contents' => $_POST['table_of_contents'],
  4. 'length' => $_POST['length']
  5. );
  6.  
  7. # Check for fields that may not be set
  8. if ( isset($_POST['lossless_copy']) )
  9. {
  10. $data = array(
  11. 'lossless_copy' => $_POST['lossless_copy']
  12. );
  13. }
  14.  
  15. // etc.
  16.  
  17. // this is an array of default values for the fields that could be in the POST
  18. $defaultValues = array(
  19. 'table_of_contents' => '',
  20. 'length' => 25,
  21. 'lossless_copy' => false,
  22. );
  23. $data = array_merge($defaultValues, $_POST);
  24. // $data is now the post with all the keys set
  25.  
  26. $optional = array('lossless_copy', 'bossless_floppy', 'foo');
  27. foreach ($optional as $field) {
  28. if (isset($_POST[$field])) {
  29. $data[$field] = $_POST[$field];
  30. }
  31. }
  32.  
  33. foreach ($_POST as $key => $value) {
  34. $data[$key] = $value;
  35. }
  36.  
  37. $fields = array();
  38. $table = 'Current_Table';
  39.  
  40. // we are not using mysql_list_fields() as it is deprecated
  41. $query = "SHOW COLUMNS from {$table}";
  42. $result = mysql_query($query);
  43. while ($get = mysql_fetch_object($result) ) {
  44. $fields[] = $get->Field;
  45. }
  46.  
  47. foreach($fields as $field) {
  48. if (isset($_POST[$field]) ) {
  49. $data[$field] = $_POST[$field];
  50. }
  51. }
  52.  
  53. $formfields = $_POST;
  54. $data = array();
  55. foreach(array_keys($formfields) as $fieldname){
  56. $data[$fieldname] = $_POST[$fieldname];
  57. }
Add Comment
Please, Sign In to add comment