我在这个网站上搜索过,但还没有找到答案。 Pr也许我无法正确应用它。我有一个表格可以抓住所有带有GALLERY_id的照片。然后,后端用户可以更改照片的标题并更改标签。提交表单后,查询应更新所有行。以下是我到目前为止没有做到的事情:
表格
if(isset($_GET['id']))
{
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM photos WHERE gallery_id = :gallery_id ");
$result->bindParam(':gallery_id', $id);
$result->execute();
echo '<form action="" method="POST">';
echo "<ul id='photos'>";
for ($i = 0; $row = $result->fetch(); $i++)
{
$id = $row['id'];
$title = $row['title'];
$tags = $row['tags'];
$src = $row['src'];
echo "<li><a class='lightbox' href='images/$src'><img src='images/$src' id='$id' alt='$title' /></a><br />";
echo "<input type='text' name='photo_title' value='$title' /><br />";
echo "<input type='text' name='photo_tags' value='$tags' />";
echo "<input type='hidden' name='photo_id' value='$id' />";
echo "</li>";
}
echo "</ul>";
}
?>
<div style="clear:both"></div>
<input type="submit" name="changeTitle" value="Save"/>
</form>
更新查询
if (isset($_POST['changeTitle']))
{
foreach ($_POST as $p)
{
$id=$p['photo_id'];
$title=$p['photo_title'];
$tags=$p['photo_tags'];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}
}
答案 0 :(得分:4)
由于您有多个具有相同名称的html字段,因此必须将它们作为数组提交:
echo "<input type='text' name='photo_title[]' value='$title' /><br />";
echo "<input type='text' name='photo_tags[]' value='$tags' />";
echo "<input type='hidden' name='photo_id[]' value='$id' />";
提交后,循环遍历任何数组变量,如
foreach ($_POST['photo_id'] as $key => $photo_id) {
$id = $photo_id;
$title = $_POST['photo_title'][$key];
$tags = $_POST['photo_tags'][$key];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}