簡體   English   中英

遍歷表單以更新SQL數據庫

[英]Loop through form to update SQL Database

我正在構建一個頁面,該頁面寫出不同數量的類別,然后在每個類別下寫出與該類別關聯的單位。 每個類別部分都是單個表單,具有重復的字段,並根據它們所屬的行進行命名。 布局是這樣的:

第1類

  • 單元1更新字段
  • 單元2更新字段
  • 單元3更新字段

類別1的提交按鈕

等等

每個字段都具有相同的名稱,並在末尾添加了單位編號:

  • Feature1,Feature2,Feature3等

給定類別中的行總數保存在變量$ id#中 ,其中#是類別的ID(例如:$ id1,$ id2,$ id3等)。

我已經解決了大部分問題。 但是,如果表單已更改,我想遍歷並執行SQL查詢,這就是我遇到的麻煩。 在這一點上,我很茫然。 這是我的代碼的簡化版本:

if (isset($_POST['submit'])) {
    $form = $_POST['form']; //save which category we're on in a variable.
    for ($i = 1; $i <= ${id.$form}; $i++) { //I think the problem is here
        $Feature = $_POST['Feature'.$i];
        $update = "UPDATE Units
               SET Feature ='$Feature'
               WHERE ID='$i'";

        if (($Feature!=${initialFeature.$i})) {
                    $updateQuery = mysqli_query($dbc, $update); 
        }
    }
}

我該如何進行這項工作? 有一個更好的方法嗎?

我要做的方法是在字段名稱中使用數組。

<input type="text" name="id[]" value="$foo">

然后在表單的操作頁面上

$id = $_POST['id'];
for($i=0;$i<sizeof($id),$i++){
   ...//do something here using $id[$i] to select elements in the array
}

我認為這就是您想要做的。

嘗試這個

for($i=0; $i<3; $i++)
    echo '<input type="text" name="feature[]" value=""/>';
echo '<input type="submit" name="go" value="submit">';

if (isset($_POST['go'])) {
    $feature = $_POST['feature'];
    if(is_array($feature)){
        for ($i = 1; $i <= count($feature); $i++) {
            $update = "UPDATE Units
               SET Feature ='$feature[$i]'
               WHERE ID='$i'";
               $updateQuery = mysqli_query($dbc, $update); 
        }
    }else{
            $update = "UPDATE Units
               SET Feature ='$feature'
               WHERE ID='$i'";
               $updateQuery = mysqli_query($dbc, $update); 
    }

}

希望這段代碼可以解決您的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM