Reputation: 9992
First of all my apopoliges , this may b a possible duplicate question, I searched and found few answered but they are not very helpfull in my case.
I have the follwing form with static and dynamic values
<input type="hidden" value="<?php echo $Quote ?>" id="amount" name="amount"/>
<input type="hidden" value="<?php echo $NoDays?>" id="total_days" name="total_days"/>
<?php $sql = mysql_query("select * from tbloffers ORDER BY Sequence"); ?>
<?php while($rows = mysql_fetch_array($sql)) { ?>
<input type="hidden" value="<?php echo $rows['Id']; ?>" name="offerid[]" />
<input type="hidden" value="<?php echo $rows['Name']; ?>" name="offername[]" />
<input type="hidden" value="<?php echo $rows['Price']; ?>" name="offercharges[]" />
<?php } ?>
<input type="email" id="customeremail" name="customeremail" required/>
And my save.php file is
$date = date("j M, Y");
$total_days = mysql_real_escape_string($_POST["total_days"]);
$amount = mysql_real_escape_string($_POST["amount"]);
$customeremail = mysql_real_escape_string($_POST["customeremail"]);
$offerid = $_POST["offerid"];
$offername = $_POST["offername"];
$offercharges = $_POST["offercharges"];
when I hit Submit I would like to be able to have all those values inserted into database through a loop. I tried foreach and struggled.
Note: The static values will repeat with dynamic values. e.g $date, $amount will remain same on Insertion.
$sql = "INSERT INTO table < What comes next?
Thanks in advance.
Upvotes: 1
Views: 2716
Reputation: 782166
You can use a foreach
loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
foreach ($offerid as $i => $offer) {
$offer = mysql_real_escape_string($offer);
$name = mysql_real_escape_string($offername[$i]);
$charges = mysql_real_escape_string($offercharges[$i]);
mysql_query("INSERT INTO table (date, total_days, amount, customer_email, offerid, offername, offfercharges)
VALUES ('$date', '$total_days', '$amount', '$customeremail', '$offer', '$name', $charges')");
}
P.S. You really should stop using the mysql extension and upgrade to mysqli or PDO, so you can use prepared queries instead of string substitution.
Upvotes: 2