从mysql数据库中删除多行

时间:2016-11-10 10:53:14

标签: php mysql

我想使用php代码从mysql数据库中删除多行这是我的代码,但我有这条消息错误如何解决这个问题?

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近''在第1行

$files_query=mysqli_query($conn,"select * from tbl_files where db_isdeleted='1'")or die(mysqli_error($conn));
          if(mysqli_num_rows($files_query)>0){
          echo"<table class='table table-hover table-responsive table-bordered'><tr>";
          echo"<td style='background:#f7ac01;font-size:16px;text-align: center;'><input type='checkbox' class='allcb' data-child='chk'/></td>
               <td style='background:#f7ac01;font-size:16px;text-align: center;'>FileName</td>
               <td style='background:#f7ac01;font-size:16px;text-align: center;'>Date</td>";
        echo"</tr>";      
          while($row=mysqli_fetch_array($files_query)){
              $id=$row['db_id'];
              $name=$row['name'];
              $date=$row['db_date'];
              echo"<tr>";
         echo'<form method="post" action="">';
        echo"<input type='hidden' name='txt_table' value='tbl_files'>";
        echo"<input type='hidden' name='txt_action' value='files'>";    
         echo"<td style='text-align: center;'><input type='checkbox' name='item[]'  class='chk'/></td>";        

         echo"<td style='text-align: center;'>$name</td>";

         echo"<td style='text-align: center;'>$date</td>";

          }
      echo"</tr>";
      echo"</table>";
            echo"<input type='submit' name='delete' value='Delete' class='btn btn-danger'>&nbsp;";
            echo"<input type='submit' name='restore' value='Restore' class='btn btn-success'>";
             echo"</form>";
      } 

/ ************************

<?php
  if(isset($_POST['delete'])){
      $table=$_POST['txt_table'];
      $action=$_POST['txt_action'];
       foreach($_REQUEST['item'] as $id) {
        // delete the item with the id $id
    $delete_query=mysqli_query($conn,"DELETE FROM {$table} WHERE db_id=$id")or die(mysqli_error($conn));
    header("location:recyclebin.php?action=$action&msg=1");       
    }
  }  
?>

1 个答案:

答案 0 :(得分:0)

抱歉我的英语。 :) 你的代码有很多问题&#34; :),但是......

使其有效的三个步骤:

首先,必须在 周期之前创建表单

echo'<form method="post" action="">';    
 while($row=mysqli_fetch_array($files_query)){

接下来,您必须提供数据库行的ID(将值=&#34; $ id&#34; 添加到复选框):

echo"<td style='text-align: center;'><input type='checkbox' name='item[]'  value="$id" class='chk'/></td>";

并在形式&#34;动作&#34; php文件中,您在FIRST迭代后重定向。在foreach循环后移动重定向:

  foreach($_REQUEST['item'] as $id) {
        // delete the item with the id $id
    $delete_query=mysqli_query($conn,"DELETE FROM {$table} WHERE db_id=$id")or die(mysqli_error($conn));

    }
header("location:recyclebin.php?action=$action&msg=1");

但是你的代码非常糟糕且不安全,请阅读:https://en.wikipedia.org/wiki/SQL_injection