Insert 2 array values ​​in mysql db

I get 2 fields from my html form that store the value in an Array .

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

I want to insert these values ​​into my mysql db. Therefore, I use the 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 shows twice the value. For example: if value 2 has value 4, etc.

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

Are you trying to do this? Each ingredient with quantity quantity?

+5
source

try it

$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;
}
+3
source
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 am such a newb, it will not allow me to comment, but if you are an echo material in your foreach, it will loop and change your values

0
source

Two loops are not needed.

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


}
0
source

Source: https://habr.com/ru/post/1523657/


All Articles