-1

Here I'm trying to insert the datas again into database new table (with quantity & customer details). $grocery_id and $grocery_item values are fetch from database. $customername, $customermobile, $groqty values are user will enter the details in that appropriate textfield.

When I execute this code ($groceryid, $groceryitem) -> These two column always stored the last row values. Because I've put the query outside of foreach loop. Here is my problem. If I put the query inside the foreach it works fine. But, quantity values doesn't work properly. So, How can I execute the query properly (outside of foreach loop)?

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

Karuppiah RK
  • 3,894
  • 9
  • 40
  • 80

1 Answers1

1

You could simply use one foreach loop considering the index values of $grocery_id and $groqty are the same.

Try:

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

    }

?>

Also note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
AyB
  • 11,609
  • 4
  • 32
  • 47