使用PDO更新多个列和行


Updating multiple columns and rows using PDO

我从一个论坛上获得了一个小片段,它允许我使用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>';

您只需要执行一个循环,绑定$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();
}