使用多个复选框更新DB

时间:2015-02-13 11:48:32

标签: php mysql

我在我的网站上制作了一个收件箱样式页面。在每封邮件旁边,我都有一个复选框

    <input type='checkbox' name='check_list[]' value='$id'>
<button class="btn btn-default" input type="submit" name="delete_button" value="Delete"> <span class="fa fa-trash"></span> Delete Selected</button>

标记为已阅读

当用户检查多个电子邮件时,我希望他们点击一个sumbit按钮,然后下一页删除所有选定的电子邮件。

我有以下PHP代码

if(!empty($_POST['check_list'])) {
    foreach($_POST['check_list'] as $check) {
            echo $check; //echoes the value set in the HTML form for each checked checkbox.
                         //so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
                         //in your case, it would echo whatever $row['Report ID'] is equivalent to.
    }
}
$result = mysql_query("UPDATE mail SET mail_deleted='1' WHERE id='$checkbox'") or die(mysql_error());

页面显示是ID 3,1和2的邮件ID(EG 312但是我不确定如何用这些更新数据库?

有人可以帮忙吗?

由于

更新

我想有2个按钮,一个用于标记为已读,另一个用于标记为已删除 我有下面的代码可以工作,但我怎么能添加未读的?

 if (isset($_POST['delete_button')) {
    if(!empty($_POST['check_list'])) {
    $check_list = $_POST['check_list'];
    $result = mysql_query("UPDATE mail SET mail_deleted='1' WHERE id IN (".implode(',', $check_list).")") or die(mysql_error());
}
}

2 个答案:

答案 0 :(得分:1)

试试这个

if(!empty($_POST['check_list'])) {
    $check_list = $_POST['check_list'];
    $result = mysql_query("UPDATE mail SET mail_deleted='1' WHERE id IN (".implode(',', $check_list).")") or die(mysql_error());
}

答案 1 :(得分:1)

<?php
    if (isset($_POST['checklist']) && count($_POST['checklist'])) {
        $dbh = NULL;
        try { 
            $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password); // connect to database
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $del = 1;
            $dbh->beginTransaction(); // execute statements in a batch
            foreach ($_POST['checklist'] as $cl) {
                // create a prepared statement and add values to it
                $stmt = $dbh->prepare("UPDATE mail SET mail_deleted = :del WHERE id = :id"); 
                $stmt->bindParam(':del', $del, PDO::PARAM_INT);
                $stmt->bindParam(':id', $cl, PDO::PARAM_INT);
                $stmt->execute(); // queue execution
            }
            $dbh->commit(); // run the batch of statements
            $dbh = NULL; // close connection
        }
        // attempt to recover from failure
        catch (PDOException $PDOex) {
            $dbh->rollback();
            $dbh = NULL;
            echo $PDOex->getMessage();
        }
        catch (Exception $ex) {
            $dbh->rollback();
            $dbh = NULL:
            echo $ex->getMessage();
        }
        // assuming things went irrecoverably wrong, still close the connection
        finally { $dbh = NULL; }
    }
?>