PHP - Deleting from DB - Error in my code?

Custom / CUSTOM
February 7, 2010 at 08:26:50
Specs: Windows XP, 8g
Hi all,

I am trying to create a form, a fragment of the
code where I believe the problem is is below. I
generate a table with a checkbox in each row
(rows showing details from DB). My aim is to
be able to check these boxes then hit delete
and have the coinsiding data removed from the
DB. At the moment when I click the DELETE
button i get taken to a blank page. Any help is
much apprieciated.

echo '<form name="input" action="test.php"
method="get">';
while($row = mysql_fetch_array($result))
{
echo "<tr>";
?>
<td> <input name="checkbox[]"
type="checkbox" id="checkbox[]" value="<?
php echo $rows['p_name']; ?>"> </td>
<?php
echo "<td>" . $row['p_name'] . "</td>";
echo "<td>" . $row['p_class'] . "</td>";
echo "<td>" . $row['p_pop_current'] . "</td>";
echo "<td>" . $row['p_pop_max'] . "</td>";
echo "<td>" . $row['p_loyalty'] . "</td>";
echo "<td>" . $row['p_land'] . "</td>";
echo "<td>" . $row['p_land_max'] . "</td>";
echo "<td>" . $row['p_ore'] . "</td>";
echo "<td>" . $row['p_mineral'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo '<input name="delete" type="submit"
id="delete" value="Delete">';

$count=mysql_num_rows($result);
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM planets WHERE
p_name='$del_id'";
}
}


See More: PHP - Deleting from DB - Error in my code?

Report •

#1
February 7, 2010 at 14:50:55
When dealing with forms, I usually do something similar to

<?php

   if(isset($_GET["delete"]) && $_GET["delete"] === "delete") {

      if(!empty($_GET["cbox"])) {
         foreach($_GET["cbox"] as $id) {
            mysql__query("delete from planets where p_name='$id'");

           if(mysql__affected__rows() == -1) {
              echo "deleting $id <b>failed</b><br />";
           } else {
              echo "deleted $id ok<br />";
           }
         }
      }

   } else { ?>

<form name="input" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="get">

check1 <input value="check1" name="cbox[]" type="checkbox"><br />
check2 <input value="check2" name="cbox[]" type="checkbox"><br />
check3 <input value="check3" name="cbox[]" type="checkbox"><br />
check4 <input value="check4" name="cbox[]" type="checkbox"><br />
check5 <input value="check5" name="cbox[]" type="checkbox"><br />
check6 <input value="check6" name="cbox[]" type="checkbox"><br />

<input name="delete" value="delete" type="submit">
</form>

<?php

   }

function mysql__query($s) {

   echo $s . "<br />";   
}

function mysql__affected__rows() {

   return (rand(50, 100) % 11 == 0 ? -1 : 1);
}
?>

I spoofed the two mysql functions, but hopefully, it will help you out in some way.

HTH


Report •

#2
February 7, 2010 at 16:55:26
Thanks very much, this did help work out my existing code.
Turns out the variables where being send over blank.

Report •
Related Solutions


Ask Question