1

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>
Benj
  • 13
  • 3
  • 1
    Please post your html code for the update & delete as well! – Timothy Kruger Mar 01 '19 at 16:48
  • Question updated. Thanks! – Benj Mar 01 '19 at 16:51
  • Thanks, this link should point you in the right direction [Update/Delete Multiple Rows using PHP](https://phppot.com/php/updatedelete-multiple-rows-using-php/)! – Timothy Kruger Mar 01 '19 at 17:16
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add any data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or data *of any kind* directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Mar 01 '19 at 17:49
  • Unless this is an academic project where the goal is learning, have you considered using a pre-existing platform like [Magento](https://magento.com)? – tadman Mar 01 '19 at 17:49

2 Answers2

1

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);
        }
    });
}
AamirR
  • 9,385
  • 3
  • 47
  • 59
  • Thanks for this sir. It works on the deletion but it has problem on updating. I have this select option after the textbox `` When this redirects to updateproduct.php, I am receiving this error **Undefined index: availability** It doesn't get the value that is selected on the dropdown. How can I get that? – Benj Mar 02 '19 at 02:30
  • I updated the answer, you have to use only **UPDATE** section, let me know if it works – AamirR Mar 02 '19 at 04:20
  • This solved the problem sir. Thanks! My question now is how can the checked data remain checked even the form is submitted? – Benj Mar 02 '19 at 05:45
  • Use **update-2** section to submit the form using ajax – AamirR Mar 02 '19 at 11:34
  • Will that make the checked data even still checked even the form is submitted? – Benj Mar 02 '19 at 11:36
  • Yes exactly, you can give it a try :) the term is *AJAX request* and here are many answers about this https://stackoverflow.com/q/1960240/1244597 – AamirR Mar 02 '19 at 11:38
  • Is there any way that we can use php to do that? Im a bit new and not familiar in JSON. – Benj Mar 03 '19 at 03:39
  • I posted a new question about this. Thanks. – Benj Mar 03 '19 at 10:32
0

You can do it by passing action during form submit for an example you have update and delete button on click of update and delete button pass action type = update or delete. either via get or post and check action in your php file.

if ($actionType === "update") doupdate(); if ($actionType === "delete") dodelete();

shivanshu patel
  • 774
  • 10
  • 18