简体   繁体   English

将2个数组值插入mysql db

[英]Insert 2 array value to mysql db

I'm getting 2 fields from my html form which store the value in an Array . 我从我的html表单中获取了2个字段,用于将值存储在Array中

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

I want to insert these 2 value to my mysql db. 我想将这两个值插入我的mysql数据库。 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. 例如:如果它是2值,它显示4个值..等等。

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 因为我是一个新手,它不会让我评论,但如果你回应你的foreach中的东西它将循环并改变你的价值观

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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