如何在for循环中使用计数器作为变量扩展?

时间:2013-04-02 17:37:44

标签: php for-loop

这是我的代码

for ($m = 1; $m <= $j; $m++)
    {
        if ($_POST['item_id".$m."'] > 0)
        {
        mysqli_query($con,"UPDATE Orders SET ProductID = '$_POST['item_id".$m."']' WHERE PO = '$k'");
        mysqli_query($con,"UPDATE Orders SET Product_Name = '$_POST['item_name".$m."']' WHERE PO = '$k'");
        mysqli_query($con,"UPDATE Orders SET Quantity_Ordered = '$_POST['item_qty".$m."']' WHERE PO = '$k'");
        }
    }

但是我得到了

  

语法错误,意外T_ENCAPSED_AND_WHITESPACE,期待T_STRING   或T_VARIABLE或T_NUM_STRING

我也试过

mysqli_query($con,"UPDATE Orders SET ProductID = '$_POST['item_qty$m']' WHERE PO = '$k'");

获得相同的结果。

有人可以帮助我吗?谢谢&gt; - :

3 个答案:

答案 0 :(得分:1)

您的报价未正确平衡。修复它们会给你:

for ($m = 1; $m <= $j; $m++)
{
    if ($_POST["item_id".$m] > 0)
    {
       mysqli_query($con,"UPDATE Orders SET ProductID = '" . $_POST["item_id".$m]   . "' WHERE PO = '$k'");
       mysqli_query($con,"UPDATE Orders SET Product_Name = '" . $_POST["item_name".$m] . "' WHERE PO = '$k'");
       mysqli_query($con,"UPDATE Orders SET Quantity_Ordered = '" . $_POST["item_qty".$m]  . "' WHERE PO = '$k'");
    }
}

答案 1 :(得分:0)

你必须在MySQL查询中转义变量:

    mysqli_query($con,"UPDATE Orders SET ProductID = '$_POST['item_id".$m."']' WHERE PO = '$k'");

    mysqli_query($con,"UPDATE Orders SET ProductID = '". $_POST['item_id".$m."'] . "' WHERE PO = '$k'");

其他人也一样。一起来:

mysqli_query($con,"UPDATE Orders SET ProductID = '". $_POST['item_id".$m."'] . "' WHERE PO = '$k'");
mysqli_query($con,"UPDATE Orders SET ProductID = '". $_POST['item_name".$m."'] ."' WHERE PO = '$k'");
mysqli_query($con,"UPDATE Orders SET ProductID = '". $_POST['item_qty".$m."'] ."' WHERE PO = '$k'");

答案 2 :(得分:0)

也许那个?

for ($m = 1; $m <= $j; $m++) {
    $item = $_POST['item_id' . $m];
    if ($item > 0) {
        $itemName = $_POST['item_name' . $m];
        $itemQty = $_POST['item_qty' . $m];
        mysqli_query($con, "UPDATE Orders SET ProductID = '" . $item . "' WHERE PO = '" . $k . "'");
        mysqli_query($con, "UPDATE Orders SET ProductID = '" . $itemName . "' WHERE PO = '" . $k . "'");
        mysqli_query($con, "UPDATE Orders SET ProductID = '" . $itemQty . "' WHERE PO = '" . $k . "'");
    }
}