How iterate through controls in a form?
I'm pretty new to PHP and I'm currently working on my first PHP website. I have a need to display (and add/edit) rows in a table in a single form.
What I'm going for is a row in the form for each row in the table plus one blank开发者_运维技巧 row so the user can add more items into the table.
When they click the save button I want all the existing rows to update and the new row (if data present) to insert.
Is there an easy way I can iterate through all the controls in a form or something of the sort?
You can iteratore through the $_POST array using the foreach construct, but do not forget to validate the key names against column names (or row names, I can't grasp your database design, probably because I just woke up).
foreach($_POST as $key => $value)
{
// do stuff
}
And if it's your first PHP website, also don't forget about SQl injection.
I usually add the number of the row to each control:
<input type='text' name='email_1'> ...
<input type='text' name='email_2'> ...
<input type='text' name='email_3'> ...
and then just roll through:
<? for ($i = 1; $i <= {max number of rows}; $i++)
{
if (isset($_POST["email_$i"]))......
this leads to a number of redundant loops, but the performance hit is negligible IMO, and the code to process the fields looks nicer, especially when you are dealing with many fields in a row.
You can also go through the actual passed POST values as the other answers suggest, which has no overhead. You'll have, however, to check each member of POST for whether it's one of your row elements, and which one. It's down to what you like better.
PHP doesn't deal with forms, only form data.
// Cycle through each item POSTED (excludes GET, and FILES)
foreach ($_POST as $data) {
echo $data . "<br/>";
}
That being said, I wouldn't suggest blindly cycling through $_POST
. Instead, know what you're looking for, and watch for it:
foreach ($_POST["emails"] as $email) {
if (!valid($email)) $errors["emails"] = "Provide valid email addresses.";
}
You can associate many email address across many rows by using array-like syntax for their name:
<input type="text" name="emails[]" value="jane.doe@somedomain.com" />
<input type="text" name="emails[]" value="john.doe@somedomain.com" />
You can get all of the fields in your table with a query. In MySQL, it would be
SHOW FIELDS FROM table_name;
Then you could loop over those fields to output the form fields (though you may have to hard-code some logic to handle what's a textbox, what's a checkbox, etc.). When submitted, you can get the fields with
foreach ($_POST as $field_name => $posted_data)
EDIT: also, given how easy this makes it to tie form field to database tables, be very careful about SQL Injection, as mentioned in another answer.
精彩评论