一个查询中有多个Mysql更新

时间:2014-12-17 19:13:56

标签: php mysql pdo

我正在尝试使用 PDO MYSQL 更新不同行的相同字段,我生成一个带有语句的表,然后传递id& "导致" (状态更新)到php,以下是我的表的代码,但是当我去更新时,首先它告诉我有很多绑定参数,即使我为表生成的所有字段输入一个值,它仍然不会更新表!

<form action='' method='POST'>
<table width="auto" class="table table-bordered table-hover">
    <tr>
<th class='col-md-1'>ID</th>
<th class='col-md-1'>User ID</th>
<th class='col-md-1'>Name</th>
<th class='col-md-1'>Date submited</th>
<th class='col-md-1'>Date Requested</th>
<th class='col-md-1'>Status</th>
</tr>

<?php
$sql = "SELECT * FROM data";
$sth = $pdo->query($sql);
$count= $sth->rowCount();
while($row = $sth->fetch()) {

echo "<tr>";
echo "<td>" . $row['id']. "</td>";
echo "<td>" . $row['user_id']. "</td>";
echo "<td>" . $row['Name']. "</td>";
echo "<td>" .$row['Date_submited']. "</td>";
echo "<td>" .$row['Date_requested']. "</td>";
echo "<td>" .$row['Status']. "</td>";
echo "<td> <select name='Status[]' value=''> <option disabled selected='true'>Please     Select</option>  <option value='denied'>Denied</option> <option value='approved'>Approved</option> </td>";
echo "<input type='hidden' name='id[]' value='".$row['id']."' />";
echo "</tr>";
}

?>
<td>      <input type='submit' name='approve' class='btn btn-default' value='submit'/></td>
 </table>
 </form>

这是我的更新查询:

if (isset( $_POST['approve'] ) ){
$result = $_POST['Status'];
$id = $_POST['id'];
$a = count($id);
try{
$sth = $pdo->prepare('UPDATE data 
                                SET 
                                Status = :Status
                                                WHERE id = :id              
                                ');
$i = 0; 
while ($i < $a) {
    $sth->bindParam(':Status', $result[$i]);
    $sth->execute();
    $i++;
    }
    }
    catch(PDOException $e) {  
    echo "I'm sorry, but there was an error updating the database.";  
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
}

1 个答案:

答案 0 :(得分:1)

您将循环放在错误的位置,并且需要绑定所有查询参数 -

if (isset( $_POST['approve'] ) ){
    // loop through results of post array
    for($i = 0; $i < count($_POST['id']); $i++) {
        $result = $_POST['Status'][$i];
        $id = $_POST['id'][$i];
        try{
            $sth = $pdo->prepare('UPDATE data SET Status = :Status WHERE id = :id');
            $sth->bindParam(':Status', $result);
            $sth->bindParam(':id', $id);
            $sth->execute();
        }
        catch(PDOException $e) {  
            echo "I'm sorry, but there was an error updating the database.";  
            file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        }
    }
}