保存mysql,同时将数据循环到数组中,然后保存到数据库中

时间:2015-02-20 00:28:59

标签: php mysql arrays loops foreach

首先我的apopoliges,这可能是一个可能重复的问题,我搜索并发现很少回答,但他们在我的情况下不是很有帮助。

我有以下形式的静态和动态值

<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/>

我的save.php文件是

$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"];

当我点击提交时,我希望能够通过循环将所有这些值插入到数据库中。我试过foreach并且挣扎。

注意:静态值将重复动态值。 例如$ date,$ amount在Insertion上保持不变。

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

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以使用foreach循环遍历其中一个重复输入,然后使用索引访问其他输入中的相应元素:

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。你真的应该停止使用mysql扩展并升级到mysqli或PDO,这样你就可以使用准备好的查询而不是字符串替换。