tags:

views:

102

answers:

5

i noticed that when posting a form the fields come out as an array.

like if i do

if(isset($_POST['submit'])) {
print_r($_POST);
}

what i usually do for form fields is the following.

lets say i have something like this (this is how i usually do it)

<form method="POST" action="">
<label>First Name: </label>
<input type="text" name="fname">

<label>Last Name: </label>
<input type="text" name="lname">

<label>Phone: </label>
<input type="text" name="phone">

<input type="submit" name="submit" value="submit">
</form>

then i'll have (im excluding field validation to make it look clear)

if(isset($_POST['submit'])) {

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];

mysql_query("insert into table(fname,lname,phone) values('$fname','$lname','$phone')");

header("Location: gosomewhere.php");

}

since the post outputs are in an array format how else can i write this when im dealing with over 100 fields?

how are the big guys doing it out there? or how are you doing it?

edit: the most ive dealth with is around 60 fields. im building this cms that takes in alot of data per form to put together information from a customer.

+5  A: 

I don't think I've ever seen anybody "dealing with over 100 fields" in a single form. If that is the case, you may consider a design-change that auto-saves portions of the data along the way. Form data will always submit itself into an array on the server-end, there's no way around this.

If you want to iterate over many fields all at once (suppose you are accepting multiple event-dates in your form), you could use the array-style naming-convention:

<input type="text" name="events[]" />

Once you access this data on the server end, you can iterate over it quickly in a simple loop:

foreach ($_POST["events"] as $event) {
  echo $event;
}

I'm sorry if I missunderstood your question.

Jonathan Sampson
its ok, the reason i asked this is because ive looked through 3rd party web applications and the form submital of fields is in no way th way i do it. alot of people do it like this but these applications have a class that read in field values and submit to the db through the class. i wonder how it does it. it was alot of work to go through and find out how their doing it.
sarmenhbbb
@sarmenhbbb: Maybe you want to have a look at the Zend Framework or Symfony. I guess the examples you found use a combination of ORM and some form framework. If you have to deal a lot with forms, it gets annoying some time. If you use a and least a form framework you could save a lot time ;) E.g. Zend Form: http://framework.zend.com/manual/en/zend.form.html
Felix Kling
+2  A: 

As Jonathan said, 100 fields in one form is way to much. But you can always build the SQL dynamically.

E.g:

if(isset($_POST['submit'])) {

  // allow only entries that are database fields
  $allow = array(/*whatever*/);

  $fields = array();
  $values = array();

  foreach($_POST as $field => $value) {
     if(in_array($field, $allow) {
        // Do correct output escaping etc. here !!
        $fields[] = $field;
        $values[] = mysql_real_escape_string($value);
     }
  }

  mysql_query('insert into table(' . join(',', $fields) . ' values(' . join(',', $values) . ')');
}

This assumes that your form fields names are the same as your DB column names.

If, as Cyro says, array_keys and array_values preserve order, then this can be done even nicer:

function clean($value, $field, &$params) {
    if(in_array($field, $params['allow']) {
       // custom validation goes here
       $params['data'][$field] = mysql_real_escape_string($value);
    }
} 

if(isset($_POST['submit'])) {

  // allow only entries that are database fields
  $allow = array(/*whatever*/);

  $params = array('allow' => $allow, 'data' => array());

  array_walk($_POST, 'clean', $params);

  if(!empty($params['data'])) {
      mysql_query('insert into table(' . join(',', array_keys($params['data'])) . ' values(' . join(',', array_values($params['data'])) . ')');
  }
}

See array_walk

Felix Kling
how would you do that? if you dont mind can you show me?
sarmenhbbb
+1  A: 

If your form contains over 100 fields, I'd worry much more about the client side than the server side. Consider using something like jQuery UI Tabs to split the form up into multiple areas, separated using fieldsets, to enhance usability.

One way around the array issue would be to use something like PHP's extract function, but I wouldn't recommend this for security reasons, and because it wouldn't really make the data any easier to work with.

John McCollum
A: 

If your form field names directly relate to your database table columns you can dynamically build your query from the $_POST array. From your example you could do:

$allowed_fields = array('fname', 'lname', 'phone');
foreach($_POST as $key => $value) {
  // if this isn't an expected field (user-injection) ignore it
  if(!in_array($key, $allowed_fields))
    continue;

  // do validation checks and data clean up here in a switch
  $data[$key] = mysql_real_escape_string($value);
}
mysql_query("INSERT INTO table(`" . implode('`, `', array_keys($data)) . "`) VALUES('" . implode("', '", array_values($data)) . "')");

Really though, a form with 100+ fields is not something I would ever fill out and I don't believe I'm alone in that. Consider breaking it up into multiple steps as others have suggested or try re-approaching your initial design.

Cryo
Are you sure that `array_keys()` and `array_values()` preserve order? Couldn't find anything about it.
Felix Kling
@Felix Yes, I've used them countless times and had no issues.
Cryo
@Cryo: using column names as form input names discloses information and is thus a security risk. It's not considered best practice.
outis
+1  A: 

The best way of dealing with so many fields is to reduce the number of fields. No one wants to have to fill out scores of fields.

Failing that, PDO has much to offer by supporting prepared statements. One thing are parameters, which (unlike your sample code) aren't vulnerable to SQL injection. Parameters can also be used to more easily construct a query using values from an array.

$query = $db->prepare("INSERT INTO table (surname, given_name, main_phone, ...) 
    VALUES (:fname, :lname, :phone, ...)");

$values = array()
foreach($_POST as $key => $val) {
    $values[':' + $key] = $val;
}
try {
    $query->execute($values);
} catch (PDOException $exc) {
    ...
}

The list of column names can be defined elsewhere, or automatically generated, then imploded when creating the prepared statement.

outis