2013-12-11 2 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

당신은 최고의 사람입니다. 그것은 아직도 내가 20 열을 가지고 모든 행을 일반화 할 수 알아 내려고, 침몰하지 않습니다, 나는 항상 각각의 수를 비교해야합니까, 롤. –

+1

@ user1824371 사용자가 제출 한 데이터에 대한 것은 ** 절대로 ** 신뢰해서는 안된다는 것입니다. 어쨌든'foreach' 루프 안에서'$ id' 키가 체크되어 지므로 카운트 비교를 할 필요가 없습니다. – Phil