简体   繁体   中英

Insert 2 array value to mysql db

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.

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?

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;
}

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


}
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM