Jump to content

[SOLVED] PHP update multiple rows


rvdb86

Recommended Posts

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!

Link to comment
https://forums.phpfreaks.com/topic/141120-solved-php-update-multiple-rows/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.