4

I'm getting 2 fields from my html form which store the value in an Array.

$ingredients = $_POST['ingredients'];
$quantity = $_POST['quantity'];

I want to insert these 2 value to my mysql db. So I'm using following:

foreach($ingredients  as $in)
{
    foreach($quantity as $q)
    {
        echo "Intredent and quantity is : $in and $q<br/>"; 

        //$insert = my mysql Insert query;
    }
}

But it showing twice value. For ex: if it's 2 value it's showing 4 value.. etc.

1
  • have you check my answer Commented Jan 25, 2014 at 5:43

4 Answers 4

5
foreach($ingredients as $key => $in)
{
    echo "Intredent and quantity is : $in and $_POST['quantity'][$key]<br/>";
}

Are you trying to do that? Each ingredient with the quantity amount?

Sign up to request clarification or add additional context in comments.

2 Comments

@Nikoia I'm trying it now.
@Babu you're welcome :) Also, welcome to StackOverflow, you can check the tour
3

try this

$ingredients = $_POST['ingredients'];
$quantity = $_POST['quantity'];

$arr_count = sizeof($ingredients);

for($i=0; $i<$arr_count; $i++)
{
    $in = $ingredients[$i];
    $q = $quantity[$i];

      echo "Intredent and quantity is : $in and $q<br/>"; 

       //$insert = my mysql Insert query;
}

Comments

1

The two loops are not necessary.

foreach($ingredients as $index => $in)
{
        echo "Intredent and quantity is : $in and $quantity[$index]<br/>";
        mysql_query("INSERT INTO <table>(<column1>,<column2>) VALUES ($in, $quantity[$index])");


}

Comments

0
if (isset ($_POST["ingredients"]) && isset($_POST["quantity"]))
{
        $sql = "insert into <table> <column1> = ".mysql_real_escape_string($_POST["ingredients"]).", <column2> = ".ctype_digit($_POST["quantity"]);
        mysql_query($sql);
        //echo your values here
}

since I'm such a newb it won't let me comment but if you echo stuff in your foreach it will loop through and change your values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.