Looking to Delete Table Entries?

This is a working script that lists the table entries then deletes the ones selected.

The script:
[php]

<?php mysql_connect("localhost", "forumdb", "asd123"); mysql_select_db("forumdb"); $checked = $_POST['checked']; foreach ($checked as $value) { mysql_query("DELETE FROM `forumdb`.`topictbl` WHERE `topictbl`.`topicid` = $value") or die(mysql_error()); } ?> <?php $result = mysql_query("SELECT * FROM topictbl"); while($row = mysql_fetch_array($result)) { echo "" . $row['topicname'] . "
"; } ?> [/php]

The explanation . . .

First, we’ll have this:

<?php
mysql_connect("localhost", "user", "pass");
mysql_select_db("topicdb");

Simple enough, right? We’re just connecting to mysql. Next, we want to find every checkbox selected, so we’ll add to that code:

$checked = $_POST['checked'];
foreach($checked as $value) {
  mysql_query("DELETE FROM `forumdb`.`topictbl` WHERE `topictbl`.`topicid` = $value") or die(mysql_error());
}
?>

$checked is all the variables we got from the form. Then it does foreach loop, which means for each checked checkbox, do this. Then it runs a simple mysql query that delets the entry by id. To write the form, then, we have this:

<form action="index.php" method="POST">
<?php
  $result = mysql_query("SELECT * FROM topictbl");
  while($row = mysql_fetch_array($result)) {
    echo "<input type='checkbox' name='checked[]' value='" . $row['topicid'] . "' />" . $row['topicname'] . "<br />";
  }
?>

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

Pretty self-explanatory; while Selecting * from topictbl, write the checkbox. :wink:

Thanks for this! Are there any security measures you recommend for using this feature front-end like you have? So far all I’ve done is declared that admins are the only ones who are allowed access to this.

I’d secure the post data to be on the safe side

[php]$checked = mysql_real_escape_string($_POST[‘checked’]);[/php]

I seem to be getting the error: Invalid argument supplied for foreach()

Is that because you did not cast the foreach in to an array?

I think the error comes from no records in the database.

Sponsor our Newsletter | Privacy Policy | Terms of Service