简体   繁体   中英

Save mysql while loop data into arrays and then save into database

First of all my apopoliges , this may ba 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. eg $date, $amount will remain same on Insertion.

$sql = "INSERT INTO table < What comes next?

Thanks in advance.

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')");
}

PS You really should stop using the mysql extension and upgrade to mysqli or PDO, so you can use prepared queries instead of string substitution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM