rvdb86 Posted January 16, 2009 Share Posted January 16, 2009 Hi, I have a form that it's input fields are created dependant on data from a table for example: tbl_categories has 3 rows so the form has 3 input fields. I want the user to be able to update the name of the categories, thereby updating the table by submitting the form, this is my code so far but it does not seem to work ??? form.php $query = "SELECT * FROM tbl_categories"; $result = mysql_query($query) or die ("Couldn't execute query"); $count=mysql_num_rows($result); while ($row = mysql_fetch_array($result)) { extract($row); echo " <tr> <td> <input name=\"cat_id".$counter."\" type=\"hidden\" value=\"$category_id\"> <input name=\"cat_name".$counter."\" type=\"text\" value=\"$category_name\" /> </td> </tr> "; $counter++; } update.php $i=1; while ($i != $_POST['count']){ $query = "UPDATE ".$_POST['table']." SET category_name='".$_POST['cat_name[$i]']."' WHERE category_id='".$_POST['cat_id[$i]']."'"; $result = mysql_query($query) or die("Couldn't update category."); $i++; I would really appreciate any help any one could offer! Quote Link to comment https://forums.phpfreaks.com/topic/141120-solved-php-update-multiple-rows/ Share on other sites More sharing options...
premiso Posted January 16, 2009 Share Posted January 16, 2009 It would be much easier to do it this way: echo " <tr> <td> <input name=\"cat_id[]\" type=\"hidden\" value=\"$category_id\"> <input name=\"cat_name[]\" type=\"text\" value=\"$category_name\" /> </td> </tr> "; foreach ($_POST['cat_id'] as $key => $id) { $query = "UPDATE ".$_POST['table']." SET category_name='".$_POST['cat_name'][$key]."' WHERE category_id='".$id."'"; $result = mysql_query($query) or die("Couldn't update category." . mysql_error()); } Although I am confused why you would pass the table name via post. That is a massive potential security flaw. Quote Link to comment https://forums.phpfreaks.com/topic/141120-solved-php-update-multiple-rows/#findComment-738606 Share on other sites More sharing options...
rvdb86 Posted January 16, 2009 Author Share Posted January 16, 2009 Thanks so much for the quick reply, everything is working now. I'm only passing the table name via post while the system is in the development stage, i still have a lot of things to work on. once again thanks alot! Quote Link to comment https://forums.phpfreaks.com/topic/141120-solved-php-update-multiple-rows/#findComment-738615 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.