Search code examples
phpmysqlsqldatabasesql-delete

I'm trying to delete the rows selected with checkboxes with php code


I'm trying to delete the rows selected with checkboxes with php code. html part

<form action="maincontrol.php" name="control" method="post">
<?php
require('dbconnect.php');

$result = mysql_query("SELECT * FROM soru");

echo "<table border='1' id='tumveriler'>
<tr>
<th></th>
<th>Index</th>
<th>Soru</th>
<th>Sorma Tarih</th>
<th>Cevap</th>
<th>Cevaplama Tarih</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . "<input name='checkbox' type='checkbox' value='" . $row['index'] . "'" . " />";
  echo "<td>" . $row['index'] . "</td>";
  echo "<td>" . $row['soru'] . "</td>";
  echo "<td>" . $row['sormadate'] . "</td>";
  echo "<td>" . $row['cevap'] . "</td>";
  echo "<td>" . $row['cevapdate'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);

?>
<input type= "submit" name ="update" value="Update">
</form>

php part

<?php
  require('dbconnect.php');

  if (isset($_POST['control']) && !empty($_POST['checkbox'])) {

    foreach($_POST['checkbox'] as $id) 

    {
        $query = "DELETE FROM soru WHERE `index` = '$id'";
        $link = mysql_query($query);

    if(!$link)
        {
        die('not worked: ' . mysql_error());
        }
        else
        {
        mysql_close($con);  
        echo 'worked';
        }


    }
  }

?>

When I click update button I see a beautiful white screen. Nothing happens, no error dialogs... Help!


Solution

  • Two things:

    • Your code is checking for the existence of $_POST['control'] which does not exist in the form (at least in the part you posted)
    • If you want the checkbox data to be submitted as an array you need to use array notation for the form:

      <input type="checkbox" name="checkbox[]" ...etc

    otherwise only the last element that was checked will get submitted.