【问题标题】:Updating multiple columns and rows using PDO使用 PDO 更新多列和多行
【发布时间】:2013-12-11 22:52:02
【问题描述】:

我从forum 中选择了一个小 sn-p,它允许我使用 PDO 更新多行。该示例仅允许单列,但我希望它可以启用按列更新。

我稍微修改了sn-p,问题是,row(url)中的单个更改将更改row(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>';

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

    你只想做一个循环,绑定$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();
    }
    

    【讨论】:

    • 你是最好的人。它仍然没有陷入困境,试图弄清楚我该如何概括这一点,每行有 10 列,我是否需要总是计算比较每一列,哈哈。
    • @user1824371 关于用户提交的数据,你应该永远信任它。我想你真的不需要做那个计数比较,因为 $id 键在 foreach 循环中被检查了
    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2014-10-26
    • 2017-03-19
    • 1970-01-01
    • 2012-08-16
    • 2013-05-02
    • 1970-01-01
    相关资源
    最近更新 更多