doushijia5684 2019-03-01 16:43
浏览 66
已采纳

更新/删除多个已检查数据

My system can update multiple data using a checkbox. This is the code I used.

The updateproduct.php contains this code.

<?php
    if (count($_POST["selected_id"]) > 0 ) {
      $db = mysqli_connect('localhost', 'root', '', 'shoopingcart');
      $all = implode(",", $_POST["selected_id"]);
      $availability=$_POST['availability'];
      $query="UPDATE internet_shop SET availability = '$availability' WHERE 1 AND id IN($all)";
      if(mysqli_query($db,$query)){
          $_SESSION['success'] = 'Products have been deleted successfully.';
      }
    }else{
        $_SESSION['error'] = 'Select checkbox to delete product.';
    }
    header("Location:testproduct.php");
?>

Now there is also an option to delete the checked items. I tried using this code on delete.php

<?php
    if (count($_POST["selected_id"]) > 0 ) {
       $db = mysqli_connect('localhost', 'root', '', 'shoopingcart');
      $all = implode(",", $_POST["selected_id"]);
      $query="DELETE FROM internet_shop WHERE 1 AND id IN($all)";
      if(mysqli_query($db,$query)){
          $_SESSION['success'] = 'Products have been deleted successfully.';
      }
    }else{
        $_SESSION['error'] = 'Select checkbox to delete product.';
    }
    header("Location:testproduct.php");
?>

This delete.php is not working due to $_POST["selected_id"] is only in one form and the action of that form redirects to updateproduct.php.

How can I delete/ update multiple data? Thank you! Below is the html code

<form name="actionForm" action="updateproduct.php" method="post" onsubmit="return updateAlert();" id="updateproduct" />
                            <table cellpadding="1" cellspacing="1" id="resultTable">
                                <thead>
                                    <tr>
                                        <th style="text-align: center;"><input type="checkbox" name="check_all" id="check_all" value=""/></th>
                                        <th class="sortable">Item</th>
                                        <th class="sortable">Price</th>
                                        <th class="sortable">Category</th>
                                        <th style="text-align: center;">Action</th>
                                    </tr>
                                </thead>
                                <?php
                                    if(mysqli_num_rows($query) > 0){
                                        while($row = mysqli_fetch_assoc($query)){
                                            extract($row);
                                ?>
                                <tr>
                                    <td align="center"><input type="checkbox" name="selected_id[]" class="checkbox" value="<?php echo $id; ?>"/></td>
                                    <td class="record"><?php echo $name; ?></td>
                                    <td>₱ <?php echo $price; ?></td>
                                    <td><?php echo $category; ?></td>
                                    <td style="text-align: center;"><a rel="facebox" href="editproductetails.php?id='.$row['id'].'">Edit info</a> | <a href="#" id="'.$row['id'].'" class="delbutton" title="Click To Delete">delete</a></td>
                                </tr>
                                <?php } }else{ ?>
                                    <tr><td colspan="3">No records found.</td></tr> 
                                <?php } ?>  
                            </table>  
                            <select name="availability">
                                <option value="Test1"> 1 </option>
                                <option value="Test2"> 2 </option>
                            </select>
                            <input type="submit" class="btn btn-primary" name="btn_delete" value="Update Records" /> 
                        </form>
  • 写回答

2条回答 默认 最新

  • douciwang6819 2019-03-01 17:45
    关注

    You can update the form action before submitting using javascript/jQuery, to do this you also need to remove the submit input button and create multiple buttons, one for each action, like so:

    <table cellpadding="1" cellspacing="1" id="resultTable">
        ...
        <button id="btn_update">Update</button>
        <button id="btn_delete">Delete</button>
    </table>
    <form name="actionForm" method="post"></form>
    

    Use following script to update form and submit

    <script type="text/javascript">
    function setFormActionAndSubmit(action) {
        const checked = $("#resultTable input[name='selected_id[]']:checked");
        if (!checked.length) {
            alert("Please select an item.");
            return;
        }
    
    
        // set form action
        const form = $(document.actionForm).attr("action", action);
        checked.each(function(){
            $("<input/>", {type: "hidden", name: "selected_id[]", value: $(this).val()}).appendTo(form);
        });
        form.submit();
    }
    
    $("#btn_update").click(function() {
        setFormActionAndSubmit("updateproduct.php")
    });
    
    $("#btn_delete").click(function(){
        setFormActionAndSubmit("delete.php")
    });
    </script>
    

    UPDATE-1 You can also create separate forms for each action, it will allow you to add any additional form input elements available to particular form, like so:

    // Update Form
    <form name="updateForm" method="post" action="updateproduct.php">
        <select name="availability">
            <option value="Test1">1</option>
            <option value="Test2">2</option>
        </select>
    </form>
    
    // Delete Form
    <form name="deleteForm" method="post" action="delete.php"></form>
    

    Use following script to submit each form

    <script type="text/javascript">
    function setFormValuesAndSubmit(form) {
        const checked = $("#resultTable input[name='selected_id[]']:checked");
        if (!checked.length) {
            alert("Please select an item.");
            return;
        }
    
        form = $(form);
        form.find("[name='selected_id[]']").remove();
        checked.each(function(){
            $("<input/>", {type: "hidden", name: "selected_id[]", value: $(this).val()}).appendTo(form);
        });
        form.submit();
    }
    $("#btn_update").click(function() {
        setFormValuesAndSubmit(document.updateForm);
    });
    $("#btn_delete").click(function(){
        setFormValuesAndSubmit(document.deleteForm);
    });
    </script>
    

    UPDATE-2 to send form using AJAX replace setFormCheckboxValuesAndSubmit with following:

    function setFormCheckboxValuesAndSubmit(form) {
        const checked = $("#resultTable input[name='selected_id[]']:checked");
        if (!checked.length) {
            alert("Please select an item.");
            return;
        }
    
        form = $(form);
        form.find("[name='selected_id[]']").remove();
        checked.each(function(){
            $("<input/>", {type: "hidden", name: "selected_id[]", value: $(this).val()}).appendTo(form);
        });
        $.ajax({
            type: "POST",
            url: form.attr('action'),
            data: form.serialize(),
            dataType: "json", // UNCOMMENT THIS IF RESPONSE IS JSON Object
            success: function(responseData) {
                alert("Form submitted successfully");
                console.log(responseData);
            },
            error: function(x) {
                alert("Something went worng")
                console.log(x, x.responseText);
            }
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度