开发者

form $_POST as an array

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 th开发者_StackOverflow中文版e 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.


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.


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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜