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>";
开发者_如何学Go 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!
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.
If you want to make sure that the form was posted, instead of using isset($_POST['control'])
(which isn't sent),
use
isset($_POST['update'])
because the submit button IS sent.
As others have mentioned once your checkbox values are an array:
<input type="checkbox" name="checkbox[]" ...
You can also simplify your database query to delete all the records with a single query using the WHERE IN clause:
// Input filtering - retrieve only int values from $_POST['checkbox']
$array = array_filter($_POST['checkbox'],'is_int');
// Format array for SQL WHERE IN clause
$array = implode(',',$array);
$query = "DELETE FROM `soru` WHERE `index` IN ($array)";
Here's the solution, as per the comments above:
Your form doesn't see to include an input named "control" yet the PHP that's handling the delete has isset($_POST['control'])
. The if
statement most likely fails. Also the input for the checkboxes should include square brackets to tell PHP it's an array: <input name="checkbox[]" ... />
.
In your form, change the line that echoes the checkbox to echo "<td>" . "<input name='checkbox[]' type='checkbox' value='" . $row['index'] . "'" . " />";
and if your form doesn't include a field named "control", remove isset($_POST['control'])
from the if
statement that in the script that deletes.
精彩评论