这里我试图将数据再次插入数据库新表(包含数量和客户详细信息)。从数据库中获取$grocery_id
和$grocery_item
值。 $customername
,$customermobile
,$groqty
值是用户将在相应的文本字段中输入详细信息。
执行此代码时$groceryid
,$groceryitem
) - >这两列始终存储最后一行值。因为我把查询放在foreach循环之外。这是我的问题。如果我把查询放在foreach中它可以正常工作。但是,数量值无法正常工作。那么,我如何正确执行查询(在foreach循环之外)?
<?php
if(isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
$customername = $_POST['customername'];
$customermobile = $_POST['customermobile'];
$groqty = $_POST['groceryquantity'];
for($i = 0; $i < sizeof($groqty); $i++)
{
$groqtys = $groqty[$i];
foreach($grocery_id as $key => $index_id )
{
}
$sql = "INSERT INTO ".customer_order." SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqtys' ";
mysql_query($sql,$CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
答案 0 :(得分:1)
考虑到foreach
和$grocery_id
的索引值相同,您只需使用一个$groqty
循环。
尝试:
<?php
if (isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
// sanitizing your values
$customername = mysql_real_escape_string($_POST['customername']);
$customermobile = mysql_real_escape_string($_POST['customermobile']);
$groqty = array_map('mysql_real_escape_string', $_POST['groceryquantity']);
foreach($grocery_id as $key => $index_id)
{
$sql = "INSERT INTO " . customer_order . " SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqty[$key]' ";
mysql_query($sql, $CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
另请注意:
Please, don't use mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。