使用TICKED复选框运行行的UPDATE语句

时间:2015-10-12 09:22:32

标签: php mysql

我有一张表格,上面写着OrderID列表和订单日期。

<table border="1" style="margin: 10px 0;">
    <form action="code/update-to-dispatched.php" method="post" name="markAsDispatched">
        <?php
            foreach ($orders as $row) {
                echo "<tr class='even'>";
                echo "<td>";
                echo "<strong>Order Date:</strong> ". $row['OrderDate'] ." <br />";
                echo "</td>";                   
                echo "<td>";
                echo "<strong>Order ID:</strong> ". $row['OrderID'] ."";
                echo "</td>";
                echo "<td>";
                echo "<input type='checkbox' name='chkBox' value='1'>";
                echo "</td>";
                echo "</tr>";
            }
        ?>

        <span class="tag"><a href="javascript:checkall('markAsDispatched','chkBox',true)">CHECK ALL</a></span>
        <span class="tag"><a href="javascript:checkall('markAsDispatched','chkBox',false)">UNCHECK ALL</a></span>
        <input type="submit" name="markAsDispatched" value="MARK AS DISPATCHED" />
    </form>
</table>

如何在代码/ update-to-dispatched.php上运行UPDATE语句,从Success成功更新要调度的订单的状态(如果勾选了复选框)?这就是我已经拥有的。

<?php
    $servername = "REMOVED";
    $username = "REMOVED";
    $password = "REMOVED";
    $dbname = "REMOVED;
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);

    try {
        if(isset($_POST['chkBox'])) {
            $stmt = "UPDATE orders SET Status = :status WHERE OrderID IN (". $_POST['chkBox'] .")";
            $stmt = $conn->prepare($stmt);
            $stmt->execute(array(':status' => "Dispatched"));
            header('Location: /cms/mark-orders-dispatched.php');
        }

        else {
            echo "NO UPDATE";
        }       
    }   

    catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
    }

    $conn = null;               
?>

1 个答案:

答案 0 :(得分:0)

首先,以这种方式渲染复选框,以便您可以在具有顺序ID的数组中获取它们。

echo "<input type='checkbox' name='chkBox[]' value='$row['OrderID']'>";

现在为每个选中的复选框运行查询,如

$ids=$_POST['chkBox'];
foreach($ids as $id)
{
$stmt = "UPDATE orders SET Status = :status WHERE OrderID=$id";
$stmt = $conn->prepare($stmt);
$stmt->execute(array(':status' => "Dispatched"));
}
header('Location: /cms/mark-orders-dispatched.php');

或者简单 不带循环运行查询

 $ids=$_POST['chkBox'];
 $stmt = "UPDATE orders SET Status = :status WHERE OrderID In ".implode(",",$ids);