【问题标题】:Deleting multiple rows from database by checkboxes通过复选框从数据库中删除多行
【发布时间】:2013-06-27 00:57:31
【问题描述】:

我想通过复选框从数据库中删除多行我有“检查全部”的工作脚本,但是当我想删除一两个时,什么也没发生。

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>

删除脚本

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.";
            }
    }}

所以它的工作是检查所有,但是当我检查一两个对象时,什么也没发生,也许有人可以帮忙?

【问题讨论】:

  • 如果您查看控制台。您是否看到发布请求在“不起作用”的情况下发出? (换句话说——什么不工作?PHP 还是 JavaScript?)看起来它可以工作,如果你说它可以与许多人一起工作,那么它应该与一个人一起工作。

标签: php mysql ajax post


【解决方案1】:

Javascript
由于您使用的是 jquery,因此有更好的方法:)

<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
一个查询就足够了:)

<?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.")" );
    }
  }
?>

请记住,在客户端执行这一切并不好。
您可以对单个文件执行 POST 请求,因为您的每个 input 按钮都有一个唯一的名称。
因此,在您的PHP 代码中,您可以像这样找到点击了哪个按钮。

<?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.")" );
  }
?>

看看多么简单:) 不是吗?

【讨论】:

  • 哇,你是快人,它有效:)。可以添加另一个提交,例如激活评论并将其与此删除脚本一起使用 ajax_update_comment.php 的 url 加入?
  • 我的意思是向同一个表单添加另一个输入提交,带有相同的复选框,但是当我单击“激活”时,它应该将数据发布到 ajax_activate_comment.php。 Avtivate 按钮应该与 ajax 删除脚本分开,但我不知道这是否可能,或者我必须执行另一个 javascript。新按钮: 更新:$sql = $db->query("UPDATE cmets SET status = '1 ' WHERE id IN (".$id_array.")" );
  • 我是用单个文件完成的,非常感谢您的帮助和建议! :)
  • 啊,还有一个问题,我正在使用:window.location.reload();现在要刷新和删除 div,但我想在不刷新的情况下这样做,我尝试过:$(".aComment"+data).fadeOut('slow', function() {$(this).remove();} ); aComment 是我用于 cmets 的 div 块。但是这段代码正在淡出所有(甚至没有删除)cmets,我想我应该从复选框中获取评论 ID,但是如何?
  • 类似$("input[name='data[]']:checked").parents("div.aComment:first").remove();
猜你喜欢
  • 2015-03-18
  • 2014-09-18
  • 2017-08-19
  • 1970-01-01
  • 2018-03-09
  • 2014-05-27
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
相关资源
最近更新 更多