Jump to content

Looping form insert problem


fife

Recommended Posts

I have a looping table with a form within the loop.  see below

 

<table width="403" border="0" cellpadding="5">
    <?php $i=0; do { ?>
      <tr>
        <td width="146"><?php echo $row_rs_foods['name']; ?></td>
        <td width="147"><?php echo $row_rs_foods['price']; ?></td>
        <td width="82">
         <form action="" method="post">
          <input name="idfood" type="hidden" value="<?php echo $row_rs_foods['idfoods']; ?>" />
          <input name="adddish<?php echo $i;?>" type="submit" value="Add Meal" />
         </form>
        </td>
      </tr>
      <?php $i++; } while ($row_rs_fooditem = mysql_fetch_assoc($rs_fooditem)); ?>
   
  </table>

 

The query that inserts the form is as below

<?php 
  if(isset($_POST['adddish'])) { 
  	$food = mysql_real_escape_string($_POST['idfood']);
$menu = $_GET['menu'];
$course = $_GET['course'];

$insertq = mysql_query("INSERT INTO foodlink (idmenu, idfood, course) VALUES ('$menu', '$food', '$course')") or die(mysql_error());

  $url = "add-existing-foods.php";        
header("Location: $url"); 
}
  ?>

 

Now my submit button increments each time by 1 but I dont understand how to make the  if(isset($_POST['adddish'])) {    have the right number  so the right food is inserted each time.

Can someone please help?

Link to comment
https://forums.phpfreaks.com/topic/265198-looping-form-insert-problem/
Share on other sites

<table width="403" border="0" cellpadding="5">
    <?php 
    echo '<input name="count" type="hidden" value="'.mysql_num_rows($rs_fooditem).'">'
    $i=0; do {
    ?>
      <tr>
        <td width="146"><?php echo $row_rs_foods['name']; ?></td>
        <td width="147"><?php echo $row_rs_foods['price']; ?></td>
        <td width="82">
         <form action="" method="post">
          <input name="idfood" type="hidden" value="<?php echo $row_rs_foods['idfoods']; ?>" />
          <input name="adddish<?php echo $i;?>" type="submit" value="Add Meal" />
         </form>
        </td>
      </tr>
      <?php $i++; } while ($row_rs_fooditem = mysql_fetch_assoc($rs_fooditem)); ?>
   
  </table>

<?php 

$count = (!empty($_POST['count'])) ? intval($_POST['count']) : 0;
$i = 0;
while ($i < $count && $count != 0)
{
  if(isset($_POST['adddish'.$i])) { 
  	$food = mysql_real_escape_string($_POST['idfood'.$i]);
$menu = $_GET['menu'];
$course = $_GET['course'];

$insertq = mysql_query("INSERT INTO foodlink (idmenu, idfood, course) VALUES ('$menu', '$food', '$course')") or die(mysql_error());
        $i++;
}
}
   
header("Location: add-existing-foods.php");   ?>

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.