2013-12-11 51 views
1

我从forum拿起一小段代码,该代码段允许我使用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>'; 

回答

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(); 
} 
+0

你是最好的人。它仍然没有陷入,试图弄清楚我怎么能概括这一点,每行有10列,我需要总是数比较每个,大声笑。 –

+1

@ user1824371关于用户提交的数据的事情是,你应该从不**信任它。我想你并不需要做这样的计数比较,因为无论如何都在'foreach'循环中检查了'$ id'键 – Phil