douyi8732 2013-06-26 15:38
浏览 100
已采纳

通过复选框从数据库中删除多行

I want to delete multiple rows from database by checkboxes i have working script for "Check All" but when i want delete one or two , nothing happend.

JavaScript

<script type="text/javascript">
jQuery(function($) {
    $("form input[id='check_all']").click(function() { // triggred check

        var inputs = $("form input[type='checkbox']"); // get the checkbox

        for(var i = 0; i < inputs.length; i++) { // count input tag in the form
            var type = inputs[i].getAttribute("type"); //  get the type attribute
                if(type == "checkbox") {
                    if(this.checked) {
                        inputs[i].checked = true; // checked
                    } else {
                        inputs[i].checked = false; // unchecked
                     }
                }
        }
    });

    $("form input[id='submit']").click(function() {  // triggred submit

        var count_checked = $("[name='data[]']:checked").length; // count the checked
        if(count_checked == 0) {
            alert("Please select a comment(s) to delete.");
            return false;
        }
        if(count_checked == 1) {
            return confirm("Are you sure you want to delete these comment?");
        } else {
            return confirm("Are you sure you want to delete these comments?");
          }
    });
}); 
</script>
<script type="text/javascript">

    $(document).ready(function(){
        $('.submit').click(function(){
            var checkValues = $('input[name=data[]]:checked').map(function()
            {
                return $(this).val();
            }).get();

            $.ajax({
                url: 'resources/ajax/ajax_delete_comment.php',
                type: 'post',
                data: { data: checkValues },
                success:function(data){

                }
            });
        });
    });

</script>

HTML/PHP

<form method="post" id="form">
Check All <input type="checkbox" id="check_all" value="">

Here im displaying record from database and <input name=\"data[]\" type=\"checkbox\" id=\"data\" value=" . $row['id'] . ">

<input name="submit" class="submit" type="submit" value="Delete" id="submit">
</form>

DELETING SCRIPT

if(isset($_POST['data'])) {
    $id_array = $_POST['data']; // return array
    $id_count = count($_POST['data']); // count array

    for($i=0; $i < $id_count; $i++) {
        $id = $id_array[$i];
        $sql = $db->query("DELETE FROM comments WHERE `id` = '$id'");
        if ($sql)
            {
                echo "success";
            }
            else
            {
                echo "Failed to delete the comment.";
            }
    }}

So its work for check all, but when im checking one or two objects, nothing happend, maybe someone could help?

  • 写回答

1条回答 默认 最新

  • dongsi1944 2013-06-26 15:45
    关注

    Javascript
    Since you are using jquery there is better way :)

    <script type="text/javascript">
      var is_activate = true; // we will track which input button was clicked :)
    
      jQuery(function($) {
        $("#form input#check_all").change(function() {
          var inputs  = $("#form input[type='checkbox']");
          if ( $(this).is(":checked") ) {
            inputs.prop( "checked", true );
            // inputs.attr( "checked", true ); // if its not working
          }
          else {
            inputs.removeAttr( "checked" );
          }
        });
    
        // Track clicked button
        $("#form input[type=submit]").on("click",function(e) {
          is_activate = ( $(this).hasClass("activate_btn") ) ? true : false;
        });
    
        $("#form").submit(function(e) {
          e.preventDefault();
          var string  = ( is_activate ) ? 'activate' : 'delete';
          var data    = $(this).serialize();
          var checked = $(this).find("input[name='data[]']:checked").length;
          if ( checked == 0 ) {
            alert( "Please select a comment(s) to "+string+"." );
            return false;
          }
          var text  = "Are you sure you want to "+string+" these comment"+( ( checked == 1 ) ? "?" : "s?" );
          if ( confirm( text ) ) {
            $.ajax({
              url: 'resources/ajax/'+( ( is_activate ) ? 'ajax_activate_comment.php' : 'ajax_delete_comment.php' ),
              type: 'post',
              data: data,
              success: function( data ) {
    
              }
            });
          }
        });
    }); 
    </script>
    

    HTML

    <form method="post" id="form">
      <label>Check All</label>
      <input type="checkbox" id="check_all" value="">
    
      <label>Here im displaying record from database and</label>
      <input name="data[]" type="checkbox" id="data1" value="1">
      <input name="data[]" type="checkbox" id="data2" value="2">
    
      <!-- Activate Button -->
      <input class="activate_btn" type="submit" name="activate" value="Activate" id="submit">
      <!-- Delete Button -->
      <input class="delete_btn" type="submit" name="delete" value="Delete" id="submit">
    </form>
    

    PHP
    A single query is enough :)

    <?php
      if ( isset( $_POST['data'] ) ) {
        $id_array = $_POST['data'];
        if ( !empty( $id_array ) ) {
          $id_array = implode( ",", $_POST['data'] ); // dont forget to sanitize
          $sql = $db->query( "DELETE FROM comments WHERE `id` IN (".$id_array.")" );
        }
      }
    ?>
    

    And remember, its not good that doing this all in client side.
    You can do POST request to a single file, since your each input button has a unique name.
    So in your PHP code, you can find which button was clicked like this.

    <?php
      if ( isset( $_POST["activate"] ) ) {
        $sql  = $db->query( "UPDATE comments SET status = '1' WHERE `id` IN (".$id_array.")" );
      }
      else {
        $sql  = $db->query( "DELETE FROM comments WHERE `id` IN (".$id_array.")" );
      }
    ?>
    

    look how simple :) Isn't it?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?