在php中循环遍历多个表单输入变量

时间:2016-06-24 23:02:54

标签: php ajax

当我在php结束时循环通过Rice表单变量。一切顺利。

<input class="rice" type="text" name="rice[]" >
<input class="beans" type="text" name="beans[]" >
<input class="price" type="text" name="price[]" >

// pdo connection
foreach($_POST['rice'] as $index => $value) {
$statement= $db->prepare('INSERT INTO product(rice)values(:rice)');

$statement->execute(array(':rice' => $value));

}

现在我如何循环遍历bean和价格 然后将三种产品,米,豆和价格插入数据库。

// pdo connection
foreach($_POST['rice'] as $index => $value) {
$statement= $db->prepare('INSERT INTO product(rice,beans,price)values(:rice,:beans,:price)');

$statement->execute(array(':rice' => $value,':beans'=>$value2,':price'=>$value3));

}

2 个答案:

答案 0 :(得分:0)

你可以像这样循环遍历:

// Make sure we have same amount of everything
$riceTotal = count($_POST['rice']);
if($riceTotal  == count($_POST['beans']) && $riceTotal == count($_POST['price']){
    foreach($_POST['rice'] as $key => $value){
        $statement = $db->prepare('INSERT INTO product(rice, beans, price) VALUES(:rice, :beans, :price)');

        $statement->execute(array(':rice' => $value, ':beans' => $_POST['beans'][$key], ':price' => $_POST['price'][$key]));
    }
}

答案 1 :(得分:0)

尝试这样的事情:

$arrayRBP = array('rice','beans','price');
foreach($arrayRBP as $data) {
    foreach($postArray as $value) {
       var_dump(${$value}[$data]);
    }
}
相关问题