Reputation: 381
I have a MySQL database with the table "chapters". The table "chapters" has three columns: (1) id, (2) name, (3) password.
I am using PHP to dynamically output the data from "chapters" into text boxes. The result looks something like this:
<form name="current_chapters" method="post" action="UpdateChapters.php">
<input type = 'text' name='id' value='{$row['id']}'>
<input type = 'text' name='name' value='{$row['name']}'>
<input type = 'password' name='password' value='New Password'>
<input type = 'submit'>
</form>
Note that this page is used to reset (not display) passwords, hence the "New Password" default value.
I am looking for the best way to loop through all of that $_POST data and then update the original "chapters" table that this data originally came from.
I tried playing around with looping through $_POST via foreach and changing the input names to "id[]", "name[]", and "password[]", but it doesn't seem to be the most elegant approach, especially with the id part...you end up with things like id[0] = 133, which just seems messy.
Any recommendations on how to go about doing this?
Thanks in advance!
Upvotes: 2
Views: 1775
Reputation: 38318
You can pass in structured data using $_POST
. Which eases handling multiple fields of the same type:
<input name="book[12][name]" value="name of book 12">
<input name="book[12][password]" value="password for book12">
<input name="book[99][name]" value="name of book 99">
<input name="book[99][password]" value="password for book99">
Which will create data structure in $_POST
like the following:
[book] => Array
(
[12] => Array
(
[name] => name of book 12
[password] => password for book 12
)
[99] => Array
(
[name] => name of book 99
[password] => password for book 99
)
)
Which you can then iterate as follows:
foreach ($_POST['book'] as $book_id => $book) {
// Watch out for SQL injection
$sql = "UPDATE book SET name = '{$book['name']}', password = '{$book['password']}' WHERE id = $book_id";
}
Upvotes: 6