Justin Saints
Justin Saints

Reputation: 97

Delete multiple rows using checkbox from mysql table using PHP

I wanted a row or multiple rows to be deleted when they are selected via check boxes. But it doesn't seem to delete anything even if I select.

Here's what I come up with:

<?php
$con=mysqli_connect("localhost","root","","annualdb");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM asean_japan WHERE agency='Air'");

if(isset($_POST['delete'])) {
  $checkbox = $_POST['checkbox'];

  for($i=0;$i<count((array)$checkbox);$i++) {
    $del_id = $checkbox[$i];
    $sql = "DELETE FROM asean_japan WHERE id='$del_id'";
    $result = mysqli_query($con,$sql);
  }
// if successful, refresh same page 
if($result) {
  echo "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";
}
}
?>
<table class='page'>
  <tr>
    <th>Select</th>
    <th>Agency</th>
    <th>FileName</th>
    <th>FileType</th>
    <th>Date Received</th>
    <th>Action</th>
  </tr>
<?php
while($row = mysqli_fetch_array($result))
{
  ?>
  <tr>
    <td align='center' bgcolor='#FFFFFF'><input name='checkbox[]' type='checkbox' value='<?php echo $row['id']; ?>'></td>
    <td><?php echo $row['agency']; ?></td>
    <td><?php echo $row['filename']; ?></td>
    <td><?php echo $row['filetype']; ?></td>
    <td><?php echo $row['date']; ?></td>
    <td><a target='_blank' href='../annual/indicators/" <?php echo $row['filename']; ?>"'>OPEN</a></td>
  </tr>
</table>

<?php
}
?>
<tr>
  <td colspan="4" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" value="Delete"></td>
</tr>
<?php
mysqli_close($con);
?>

Is there a problem with my checkbox or the input=delete maybe?

Upvotes: 0

Views: 299

Answers (2)

karthik
karthik

Reputation: 1

    foreach($_POST['checkbox'] as $key =>$val) {
        if($val!='') {
             $sql = "DELETE FROM asean_japan WHERE id='$val'";
             $result = mysqli_query($con,$sql);  
        }
    }

Upvotes: 0

Pardeep K
Pardeep K

Reputation: 50

first you need to close table tag outside the while loop and then you need to check onclick your data post or not to target url click here this will help you

Upvotes: 1

Related Questions