updating multiple records from one form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sgarrett
Forum Newbie
Posts: 1
Joined: Tue Sep 06, 2005 2:51 pm
Location: Edmonton, Alberta, Canada

updating multiple records from one form

Post by sgarrett »

Hi All!

I'm looking for some help with what seems like a simple request, but as usual never is. I have a client that runs a tree nursery. We've set up the webstie and content manangement for them, but I need to be able to update the price list of each plant from one table. I can show all the plants and their prices, but can't figure out how to update with the one form. I can update the prices one by one, but that takes the client forever. They would like to see a list of plant names and prices, then be able to make the changes and then click update and have all the different records be updated. Make sense? If anyone has any ideas or suggestions that would be greatly appreicated. (This is php and MySQL code I'm looking for)

Thanks

Shelley
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

I've encountered this problem before. I've gotten through it by dynamically creating and assigning names to the fields. Usually I use the id number of the product. I retrieve a list of products to change from the database. Loop through the list of products and dynmically name the fields/checkboxes" PREFIX_".$id assign the value as $id. When the form is processed recreate the ids through the database or through a hidden field with comma deilimited possible id's. Then all you have to do is $_POST['SUFFIX_'.$possible_id] to access the variable after it's been submitted.

Hope that helps.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

As neophyte suggested your going to need a unique identifier so you can distinguish the rows in your table. This in all likelyness should be your primary key set to auto_increment. You should then loop through your database dynamically creating your form having the input fields as an array.
something like

Code: Select all

$result = 'SELECT * FROM `trees` ORDER BY `id` DESC';

.. query...

while ($row = mysql_fetch_assoc($result)) {
   echo $row['tree_name'].'-- <input type="input" name="trees['.$row['id'].']" value="'.$row['description'].'">';
}
Now that your form is built and populated, check for a submition of the form, and build your new update query

Code: Select all

foreach ($_POST['trees'] as $id => $value) {
   ... build your update query
   ... $id now contains your tree id and $value contains your tree description
}
Post Reply