15

I want to delete multiple rows from my MYSQL database table. I have created this file to select various links and delete them using checkboxes.

This doesn't seem to delete any row. My data is populated in the table. I guess the problem is with my PHP code. Please check the below code and guide me to get out from this...

<html>
  <head>
    <title>Links Page</title>
  </head>
  <body>
    <h2>Choose and delete selected links.</h2> 
    <?php
      $dbc = mysqli_connect('localhost','root','admin','sample') or die('Error connecting to MySQL server');
      $query = "select * from links ORDER BY link_id";
      $result = mysqli_query($dbc,$query) or die('Error querying database');
      $count=mysqli_num_rows($result);
    ?>
    <table width="400" border="0" cellspacing="1" cellpadding="0">
      <tr>
        <td>
          <form name="form1" method="post" action="">
            <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
              <tr>
                <td bgcolor="#FFFFFF">&nbsp;</td>
                <td colspan="3" bgcolor="#FFFFFF">
                  <strong>Delete multiple links</strong>
                </td>
              </tr>
              <tr>
                <td align="center" bgcolor="#FFFFFF">#</td>
                <td align="center" bgcolor="#FFFFFF">
                  <strong>Link ID</strong>
                </td>
                <td align="center" bgcolor="#FFFFFF">
                  <strong>Link Name</strong>
                </td>
                <td align="center" bgcolor="#FFFFFF">
                  <strong>Link URL</strong>
                </td>
              </tr> 
              <?php
  
                while ($row=mysqli_fetch_array($result)) {
              ?>
              <tr>
                <td align="center" bgcolor="#FFFFFF">
                  <input name="checkbox" type="checkbox" value="
                    <?php echo $row['link_id']; ?>">
                </td>
                <td bgcolor="#FFFFFF"> <?php echo $row['link_id']; ?> </td>
                <td bgcolor="#FFFFFF"> <?php echo $row['link_name']; ?> </td>
                <td bgcolor="#FFFFFF"> <?php echo $row['link_url']; ?> </td>
              </tr> 
              <?php
                }
              ?> 
              <tr>
                <td colspan="4" align="center" bgcolor="#FFFFFF">
                  <input name="delete" type="submit" value="Delete">
                </td>
              </tr>
            </table>
          </form>
        </td>
      </tr>
    </table>    
    <?php
      // Check if delete button active, start this
      if(isset($_POST['delete']))
      {
        $checkbox = $_POST['checkbox'];
        for($i=0; $i<count($checkbox); $i++) {
          $del_id = $checkbox[$i];
          $sql = "DELETE FROM links WHERE link_id='$del_id'";
          $result = mysqli_query($sql);
        }
        // if successful redirect to delete_multiple.php 
        if($result){
          echo '<meta http-equiv="refresh" content="0;URL=view_links.php">';
        }
      }
      mysqli_close($dbc);
    ?>
  </body>
</html>
Mano Mahe
  • 84
  • 1
  • 17
spyder
  • 330
  • 3
  • 6
  • 18
  • i am completely new to programming in PHP. Can you please let me know about any free debugging PHP tool? – spyder Jan 23 '13 at 08:18
  • 2
    turn on error reporting and learn to read the messages. – tradyblix Jan 23 '13 at 08:18
  • Also try moving that last PHP portion (isset($_POST['delete'])) to before the HTML tags to be sure none of the data is being reset when the page is submitted. Also it might help to use form tags:`
    `
    – Shawn Cheever Jan 23 '13 at 08:21
  • Add `` to the very start of the page to enable all debugging information. – Shawn Cheever Jan 23 '13 at 08:22
  • thanks guys! it was a small mistake on my part. i had "$result = mysqli_query($sql);"...checked the error logs...found out that mysqli_query() expects at least two parameters...silly on my part :) – spyder Jan 23 '13 at 08:32
  • Please be warned that the given `DELETE` query is highly vulnerable for SQL injections. Have a look at prepared statements to avoid getting hacked – Nico Haase Feb 15 '23 at 07:30

6 Answers6

16

You should treat it as an array like this,

<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">

Then only, you can take its count and loop it for deletion.

You also need to pass the database connection to the query.

$result = mysqli_query($dbc, $sql);

Yours did not include it:

$result = mysqli_query($sql);
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Edwin Alex
  • 5,118
  • 4
  • 28
  • 50
  • changed it from name="checkbox" to name="checkbox[]"....still, its not deleting any data – spyder Jan 23 '13 at 08:21
  • put echo for your delete query to see whether the data $del_id comes perfectly. If $del_id value comes perfectly, run the query in your mysql editor. you will come to know if any error in the database side – Edwin Alex Jan 23 '13 at 08:24
  • @spyder The reason why it wasn't deleting after Edwin posted his answer is that, you never passed db connection to `$result = mysqli_query($sql);`. Which should have read as `$result = mysqli_query($dbc, $sql);`. @ Edwin: I made the edit. – Funk Forty Niner Dec 06 '16 at 14:25
13

Use array notation like name="checkbox[]" in your input element. This will give you $_POST['checkbox'] as array. In the query you can utilize it as

$sql = "DELETE FROM links WHERE link_id in ";
$sql.= "('".implode("','",array_values($_POST['checkbox']))."')";

Thats one single query to delete them all.

Note: You need to escape the values passed in $_POST['checkbox'] with mysql_real_escape_string or similar to prevent SQL Injection.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
4
<?php $sql = "SELECT * FROM guest_book";
                            $res = mysql_query($sql);
                            if (mysql_num_rows($res)) {
                            $query = mysql_query("SELECT * FROM guest_book ORDER BY id");
                            $i=1;
                            while($row = mysql_fetch_assoc($query)){
                            ?>


<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>"  />

<?php $i++; }} ?>


<input type="submit" value="Delete" name="Delete" />

if($_REQUEST['Delete'] != '')
{
    if(!empty($_REQUEST['checkboxstatus'])) {
        $checked_values = $_REQUEST['checkboxstatus'];
        foreach($checked_values as $val) {
            $sqldel = "DELETE from guest_book WHERE id = '$val'";
           mysql_query($sqldel);

        }
    }
} 
4

Delete Multiple checkbox using PHP Code

<input type="checkbox" name="chkbox[]  value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
 $cnt=array();
 $cnt=count($_POST['chkbox']);
 for($i=0;$i<$cnt;$i++)
  {
     $del_id=$_POST['chkbox'][$i];
     $query="delete from $tablename where Id=".$del_id;
     mysql_query($query);
  }
}
mmohab
  • 2,303
  • 4
  • 27
  • 43
1

Something that sometimes crops up you may/maynot be aware of

Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE

As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?

If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?

Dave
  • 3,280
  • 2
  • 22
  • 40
  • i want the form to display id as a seperate column...also, i need the checkboxes to link to the primary key, which is again the link_id column..thus, the same data for both the columns – spyder Jan 23 '13 at 09:29
  • erm why not do it all in one table in a single loop there is litterally no need to loop the same dataset twice as you really are displaying identical information in both according to your code above. – Dave Jan 23 '13 at 09:31
  • i have removed one dataset/column :) – spyder Jan 23 '13 at 10:06
1
 $deleted = $_POST['checkbox'];
 $sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";