我从forum中选取了一个小片段,允许我使用PDO更新多行。该示例仅允许单列,但我希望它可以启用列式更新。
我稍微修改了片段,问题是,行(url)中的单个更改将更改行中的所有条目(url)
如果有人敏锐地看到问题是什么:
if (isset($_POST['submit'])) {
$stmt = $db->prepare("UPDATE `$tbl_name` SET `url`=:url, `country`=:country WHERE id=:id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':url', $url, PDO::PARAM_STR);
$stmt->bindParam(':country', $country, PDO::PARAM_STR);
foreach ($_POST['url'] as $id => $url) {
$stmt->execute();
}
foreach ($_POST['country'] as $id => $country) {
$stmt->execute();
}
echo '<h1>Updated the records.</h1>';
}
// Print the form.
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" method="post">';
foreach ($db->query("SELECT * FROM `$tbl_name` ORDER BY `id`") as $row) {
echo '<input type="text" name="url[' . (int)$row['id'] . ']" value="'
. htmlspecialchars($row['url']) . '" /><input type="text" name="country[' . (int)$row['id'] . ']" value="'
. htmlspecialchars($row['country']) . '" /><br />';
}
echo '<input type="submit" name="submit" value="Update" /></form>';
答案 0 :(得分:3)
你只想做一个循环,绑定$url
和$country
。像这样的东西
if (!isset($_POST['url'], $_POST['country']) || count($_POST['url']) != count($_POST['country'])) {
throw new Exception('URL / country mismatch');
}
foreach ($_POST['url'] as $id => $url) {
if (!array_key_exists($id, $_POST['country'])) {
throw new Exception("No matching country for ID $id");
}
$country = $_POST['country'][$id];
$stmt->execute();
}