[英]Loop through form to update SQL Database
I am building a page that writes out a varying number of categories and then, under each category, writes out the units associated with that category. 我正在构建一个页面,该页面写出不同数量的类别,然后在每个类别下写出与该类别关联的单位。 Each category section is a single form with fields that are repeated and named according to what row they belong to.
每个类别部分都是单个表单,具有重复的字段,并根据它们所属的行进行命名。 The layout is like this:
布局是这样的:
Category 1
第1类
- Unit 1 Update Fields
单元1更新字段
- Unit 2 Update Fields
单元2更新字段
- Unit 3 Update Fields
单元3更新字段
Submit Button for Category 1
类别1的提交按钮
etc.
等等
Each field is named the same thing with the unit number added on the end: 每个字段都具有相同的名称,并在末尾添加了单位编号:
- Features1, Features2, Features3, etc.
Feature1,Feature2,Feature3等
The total number of rows in a given category is held in the variable $id# where # is the category's ID (ex: $id1, $id2, $id3, etc). 给定类别中的行总数保存在变量$ id#中 ,其中#是类别的ID(例如:$ id1,$ id2,$ id3等)。
I've got most of this sorted out. 我已经解决了大部分问题。 However, I want to loop through and perform a SQL query if the form has been changed, and that's where I'm having trouble.
但是,如果表单已更改,我想遍历并执行SQL查询,这就是我遇到的麻烦。 At this point, I'm at a loss.
在这一点上,我很茫然。 Here is a simplified version of my code:
这是我的代码的简化版本:
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);
}
}
}
How can I make this work? 我该如何进行这项工作? Is there a better way to do this?
有一个更好的方法吗?
The way I would do it is using an array in field names. 我要做的方法是在字段名称中使用数组。
<input type="text" name="id[]" value="$foo">
Then on the action page for the form 然后在表单的操作页面上
$id = $_POST['id'];
for($i=0;$i<sizeof($id),$i++){
...//do something here using $id[$i] to select elements in the array
}
I think that is what you're trying to do. 我认为这就是您想要做的。
try this 尝试这个
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);
}
}
hope this code can solve your problem 希望这段代码可以解决您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.