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>
6
  • i am completely new to programming in PHP. Can you please let me know about any free debugging PHP tool? Commented Jan 23, 2013 at 8:18
  • 2
    turn on error reporting and learn to read the messages. Commented Jan 23, 2013 at 8: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:<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="deleteForm"> Commented Jan 23, 2013 at 8:21
  • Add <?php error_reporting(E_ALL); ?> to the very start of the page to enable all debugging information. Commented Jan 23, 2013 at 8: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 :) Commented Jan 23, 2013 at 8:32

6 Answers 6

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);
Sign up to request clarification or add additional context in comments.

3 Comments

changed it from name="checkbox" to name="checkbox[]"....still, its not deleting any data
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
@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.
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.

Comments

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);

        }
    }
} 

Comments

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);
  }
}

Comments

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 ?

3 Comments

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
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.
i have removed one dataset/column :)
1
 $deleted = $_POST['checkbox'];
 $sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.