【问题标题】:PHP / SQL: Multiple delete unsucessfulPHP / SQL:多次删除不成功
【发布时间】:2020-03-12 07:41:33
【问题描述】:

目前我已经创建了一个系统,该系统可以对从 SQL 数据库中获取并显示在 dashboard_engineer.php 的数据行列表执行多个删除操作。每个数据行都包含一个删除按钮。每行还有一个复选框,使用户能够删除选定的数据行。在数据行的底部,有一个按钮可以删除所有选中的数据行。

我的问题是多次删除,比如说,如果我选择两个数据行(id 4 和 5),它只会删除一个 ID。

下面是我的代码

dashboard_engineer2.php

<?php

    if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){

    $from = $_REQUEST['from'];
    $to   = $_REQUEST['to'];
    $team = $_REQUEST['team'];

    $result = '';
    $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid 
    WHERE ot_report.status = 'yes' AND ot_users.team_id = :team AND report_date BETWEEN :from 
    AND :to ORDER BY ot_report.report_id DESC";

    $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $sql->bindParam(':team', $team);
    $sql->bindParam(':from', $from);
    $sql->bindParam(':to', $to,);
    $sql -> execute(); 

    if($sql->rowCount() > 0){

    echo'

        <table class = "table-bordered" width = "100%">
        <thead>
        <tr>
        <th width = "10%"><input type="checkbox" id="checkAl"> All</th>
        <th width = "3%">id</th>
        <th width = "15%">Date</th>
        <th width = "25%">Supervisor</th>
        <th width = "30%">Task Name</th>
        <th width = "10%">Status</th>
        <th colspan = "2" width = "7%">Action</th>
        </tr>
        </thead>
        <tbody>';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $status=$row['report_status'];

            if($status=="Pending"){
                $color="color:blue";
            }
            else {
                $color="color:green";
            }

            $report_id = $row["report_id"];

            echo'<tr>';
                echo '<td><input type="checkbox" id="checkItem" name="check[]" value="'.$report_id.'"></td>';
                echo '<td>'.$report_id.'</td>';
                echo '<td>'.$row['report_date'].'</td>';
                echo '<td>'.$row["fullname"].'</td>';
                echo '<td>'.$row["task_name"].'</td>';
                echo '<td align="center" style='.$color.'><strong>'.$status.'</strong></td>';

                echo '<td align="center">';
                    echo '<form action = "view_task/view_task.php" method = "post" target="_blank">';
                        echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                        echo '<button type = "submit" class="btn-primary">View</button>';
                    echo '</form>';
                echo '</td>';

                echo '<td align="center">';
                    echo "<form action = 'remove2.php' method = 'post' onClick=\"return confirm('Do you want to remove this reports?')\">";
                        echo '<input type = "hidden" name = "from" value = "'.$from.'">';
                        echo '<input type = "hidden" name = "to" value = "'.$to.'">';
                        echo '<input type = "hidden" name = "team" value = "'.$team.'">';
                        echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                        echo '<button type = "submit" class="btn-danger">Remove</button>';
                    echo '</form>';
                echo '</td>';
            echo '</tr>';
            $i++;

            }

            echo '<tr>';
                echo '<td>';
                    echo "<form action = 'delete_selected.php' method = 'post'>";
                        echo '<input type="hidden" id="checkItem" name="check[]" value="'.$report_id.'">';
                        echo '<button type="submit" class="btn-danger btn-sm">DELETE</button>';
                    echo '</form>';  
                echo '</td>';
            echo '</tr>';

        }

    } 

?>

delete_selected.php

<?php

    include("../../../config/configPDO.php");
    include("../../../config/check.php");


    $checkbox = $_POST['check'];
    for($i=0;$i<count($checkbox);$i++){
        $report_id = $checkbox[$i];

        $sql = "UPDATE ot_report SET status = 'no' WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        header("Location: dashboard_engineer.php");

    }

?>

谁能帮我解决这个问题?谢谢

【问题讨论】:

  • 如果能隔离问题就更好了。确保您的表单在多次检查时提交超过 1 个值
  • 你不能有多个相同的ID,例如checkItem
  • 您在外部表单中循环...在您的删除表单中它只设置了最后一个值...
  • @RamRaider 你能用代码给出答案吗?
  • @AntonyJack 你能编辑我上面的代码吗?

标签: php sql


【解决方案1】:

好的 - 以下是基于问题的代码,但为了构建一个有效的演示,它已经被概括了。这里重要的是使用 Javascript 来维护所选 ID 的列表(通过单击 select-all 复选框或单击单个复选框。请忽略表单中生成的内容 - 日期对于本示例而言是虚假且无意义的。

您可以复制它并创建一个应该可以正常运行的测试页面 - 生成伪 SQL 的 PHP 只是显示将执行的语句而不是它应该如何执行(应该按照问题,@987654322 @)

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        if( isset( $_POST['ids'] ) ){
            $items=explode( ',', $_POST['ids'][0] );

            foreach($items as $id){
                $sql=sprintf('UPDATE ot_report SET status="no" WHERE report_id=%d',$id);
                echo $sql . '<br />';
            }
        }
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
    </head>
    <body>
        <table>
            <?php

                for( $i=1; $i <= 10; $i++ ){
                    /* example data for dates... */
                    $hrs=mt_rand(1,24);
                    $mins=mt_rand(0,60);
                    $secs=mt_rand(0,60);

                    $month=mt_rand(1,12);
                    $day=mt_rand(1,28);
                    $year=mt_rand(2000,2020);

                    $from=date('y-m-d',mktime($hrs,$mins,$secs,$month,$day,$year));
                    $to=date('y-m-d',mktime($hrs+3,$mins+20,$secs,$month,$day,$year));

                    printf('
                    <tr>
                        <td><input type="checkbox" name="check[]" value="%1$d" /></td>
                        <td>Some data %1$d</td>
                        <td>
                            <form method="post">
                                <input type="hidden" name="from" value="%2$s" />
                                <input type="hidden" name="to" value="%3$s" />
                                <input type="hidden" name="id" value="%1$d" />
                                <input type="submit" />
                            </form>
                        </td>
                    </tr>', $i, $from, $to );
                }

            ?>
        </table>
        <form method='post'>
            <input type='checkbox' name='selectall' value='Select-All' />
            <input type='hidden' name='ids[]' />
            <input type='button' name='sub-delete' value='Update selected' />
        </form>
        <script>
            let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
            let tmp=[];

            document.querySelector('[name="selectall"]').addEventListener('change',function(e){
                let col=document.querySelectorAll('[name="check[]"]');
                col.forEach(chk=>{
                    chk.checked=this.checked;
                    if( this.checked )tmp.push(chk.value)
                    else tmp.splice(tmp.indexOf(chk.value),1)
                });
            });

            document.querySelectorAll('[name="check[]"]').forEach( chk=>{
                chk.addEventListener('change',function(e){
                    if( this.checked )tmp.push(this.value)
                    else tmp.splice( tmp.indexOf(this.value),1);
                });
            });

            document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
                ids.value=tmp.join(',')
                this.parentNode.submit()
            });
        </script>
    </body>
</html>

将生成类似于:

UPDATE ot_report SET status="no" WHERE report_id=10
UPDATE ot_report SET status="no" WHERE report_id=8
UPDATE ot_report SET status="no" WHERE report_id=6
UPDATE ot_report SET status="no" WHERE report_id=4

快速尝试使用您的代码调整此示例:

<?php
    if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
        $from=$_REQUEST['from'];
        $to  =$_REQUEST['to'];
        $team=$_REQUEST['team'];

        $result='';
        $query="SELECT * FROM ot_report 
                LEFT JOIN ot_users ON ot_report.badgeid=ot_users.badgeid 
                WHERE ot_report.status='yes' AND ot_users.team_id=:team AND report_date BETWEEN :from AND :to 
                ORDER BY ot_report.report_id DESC";

        $sql=$conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql->bindParam(':team', $team);
        $sql->bindParam(':from', $from);
        $sql->bindParam(':to', $to);
        $sql->execute();





        if($sql->rowCount() > 0){
            echo'
            <table class="table-bordered" width="100%">
                <thead>
                <tr>
                    <th width="10%"><input type="hidden" name="selectall" value="Select-All">All</th>
                    <th width="3%">id</th>
                    <th width="15%">Date</th>
                    <th width="25%">Supervisor</th>
                    <th width="30%">Task Name</th>
                    <th width="10%">Status</th>
                    <th colspan="2" width="7%">Action</th>
                </tr>
            </thead>
            <tbody>';

            $i=0;

            while($row=$sql->fetch(PDO::FETCH_ASSOC)){
                $status=$row['report_status'];

                if($status=="Pending"){
                    $color="color:blue";
                } else {
                    $color="color:green";
                }

                $report_id=$row["report_id"];

                echo'
                <tr>
                    <td><input type="checkbox" name="check[]" value="'.$report_id.'"></td>
                    <td>'.$report_id.'</td>
                    <td>'.$row['report_date'].'</td>
                    <td>'.$row["fullname"].'</td>
                    <td>'.$row["task_name"].'</td>
                    <td align="center" style='.$color.'><strong>'.$status.'</strong></td>

                    <td align="center">
                        <form action="view_task/view_task.php" method="post" target="_blank">
                            <input type="hidden" name="report_id" value="'.$report_id.'">
                            <button type="submit" class="btn-primary">View</button>
                        </form>
                    </td>

                    <td align="center">
                        <form action="remove2.php" method="post" onsubmit="return confirm(\'Do you want to remove this reports?\')">
                            <input type="hidden" name="from" value="'.$from.'">
                            <input type="hidden" name="to" value="'.$to.'">
                            <input type="hidden" name="team" value="'.$team.'">
                            <input type="hidden" name="report_id" value="'.$report_id.'">
                            <button type="submit" class="btn-danger">Remove</button>
                        </form>
                    </td>
                </tr>';

                $i++;
            }

            echo '
            <tr>
                <td>
                    <form action="delete_selected.php" method="post">
                        <input type='hidden' name='ids[]' />
                        <input type='button' name='sub-delete' value='DELETE' />
                    </form>
                </td>
            </tr>';
        }
    }
?>
<script>
    let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
    let tmp=[];

    document.querySelector('[name="selectall"]').addEventListener('change',function(e){
        let col=document.querySelectorAll('[name="check[]"]');
        col.forEach(chk=>{
            chk.checked=this.checked;
            if( this.checked )tmp.push(chk.value)
            else tmp.splice(tmp.indexOf(chk.value),1)
        });
    });

    document.querySelectorAll('[name="check[]"]').forEach( chk=>{
        chk.addEventListener('change',function(e){
            if( this.checked )tmp.push(this.value)
            else tmp.splice( tmp.indexOf(this.value),1);
        });
    });

    document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
        ids.value=tmp.join(',')
        this.parentNode.submit()
    });
</script>

delete_selected.php

<?php

    include("../../../config/configPDO.php");
    include("../../../config/check.php");


    $checkbox=explode( ',', $_POST['ids'][0] );

    for($i=0;$i < count($checkbox); $i++){
        $report_id=$checkbox[$i];

        $sql="UPDATE ot_report SET status='no' WHERE report_id=:report_id";
        $query=$conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        header("Location: dashboard_engineer.php");

    }

?>

【讨论】:

  • 哪一部分你不明白-创建伪sql的PHP,生成初始页面的php还是javascript?
  • @javascript, mktime??
  • 忽略生成页面的 php(尤其是 mktime ),因为这只是为了帮助生成 realistic 示例。重要的是 checkbox 的名称为 check[] ~ 它当时不在表单中(这就是您的代码的样子),因此不会出现在 POST 数组中。 javascript 用于记录任何选中的复选框并将提交表单。表单提交在此阶段填充了所有复选框值( ids ),因此 ids[] 字段中保存的值可用于 PHP 处理
  • 尝试复制上述内容,保存到您的服务器并运行 - 这可能有助于理解我所说的
  • 已经在使用你的代码了。但是全选复选框,您将其删除。我也想用复选框来勾选所有框
猜你喜欢
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多