从while循环输入数组,为每个输入传递$ _POST

时间:2017-04-11 16:52:18

标签: php mysql arrays sql-parametrized-query

<form role="form" autocomplete="off" action="includes/functions/fisa-init.php" method="POST">
<?php
   connectDB();
   $query = mysqli_query($mysqli, "SELECT * FROM `optionale`") or die(mysqli_error($mysqli));
   while($row = mysqli_fetch_array($query))
   { 
?>
   <span><?php echo $row['denumire']; ?></span>
   <input type="text" name="nrBucati[]">
   <input type="hidden" value="<?php echo $row['cod']; ?>" name="codProdus[]">
<?php } ?>
</form>

在while循环中,我得到了input name="nrBucati[]"input name="codProdus[]"的数组。

我有查询:

$stmt3 = $mysqli->prepare("
            UPDATE 
            `stocuri` 
            SET 
            `cantitate` = `cantitate` - ?
            WHERE `cod` = ?
            ");


    $stmt3->bind_param("is", $bucata, $cod);

    // set parameters and execute
    foreach( $_POST['nrBucati'] as $bucata ) {
    return $bucata; 
    }

    foreach( $_POST['codProdus'] as $cod ) {
    return $cod;
    }

    if (!$stmt3->execute()) 
        {
            echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
        }
    $stmt3->close();

我无法通过$_POST获取所有输入数组值。详细信息:

While loop - Only one input from many others is sending a value through POST

如何通过POST从HTML中获取数组nrBucati[]codProdus[]的每个输入值?

2 个答案:

答案 0 :(得分:0)

这样的东西可以正确分配/配对你的两个参数,然后在循环中执行你的查询调用。

foreach( $_POST['nrBucati'] as $id => $bucata ) {
    $cod = $_POST['codProdus'][$id];

    if (!$stmt3->execute()) 
        {
            echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
        }
}

答案 1 :(得分:0)

运行foreach并在foreach循环中准备数据:

// Get posted data and execute
foreach( $_POST['nrBucati'] as $key=>$bucata ) {
    $cod = $_POST['codProdus'][$key]; // For object change this to $_POST['codProdus']->$key;

    $stmt3= $mysqli->prepare("UPDATE `stocuri` SET `cantitate` = `cantitate` - ? 
                              WHERE `cod` = ? ");
    $stmt3->bind_param("is", $bucata, $cod);

    if (!$stmt3->execute()){

        echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
    }

    $stmt3->close();

}