在foreach循环查询之外没有正常工作

时间:2014-04-01 09:36:15

标签: php mysql loops for-loop foreach

这里我试图将数据再次插入数据库新表(包含数量和客户详细信息)。从数据库中获取$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.");
        }
    }
?>

enter image description here

1 个答案:

答案 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,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial