Hi all, I am learning php and am having problems working out how to use a dynamically populated select list to DELETE rows in a simple database.

I have set the database up, I can add, edit and delete rows using simple forms I created. I have also set up a separate dynamic select drop down list that shows the entries. This works fine.

What I want to do is use this select list to delete entries. The code for the select list at the moment just looks like this:


<FORM method="post" action="delete.php">

<select name="counties">
<?php
$sql = "SELECT id, countyname FROM counties ".
"ORDER BY countyname";

$rs = mysql_query($sql);

while($row = mysql_fetch_array($rs))
{
  echo "<option value=\"".$row['id']."\">".$row['countyname']."\n  ";
}


?>
</select>
<input type="submit" />
</form>

I have managed to delete entries using a form and the following query


mysql_query("DELETE FROM counties WHERE countyname = '$_POST[countyname]'");

But the problem is, you have to manually type the countyname in the text field to delete it. I want to select it from the dynamic dropdown, then a submit button.

I've searched google for similar examples but had no luck!

It's probably really simple, but since I am very new to php im struggling!

Many thanks!

    gather the ID's as an array (and use the "multiple" tag so you can delete more than 1 at a time)

    <form method="post" action="delete.php">
    <select name="counties[]" multiple>
    
    <?php
    $sql = 'SELECT id, countyname FROM counties ORDER BY countyname';
    $result = mysql_query($sql) or exit(mysql_error());
    while ($row = mysql_fetch_assoc($result))
    {
      echo '<option value="' . $row['id'] . '">' . $row['countyname'] . '</option>';
    }
    ?>
    
    </select>
    <input type="submit">
    </form>
    

    then in delete.php

    <?php
    $sql = 'DELETE FROM counties WHERE id IN(' . implode(',', $_POST['counties']) . ')';
    ?>
    

      Thank you, that worked a treat! 🙂

        Write a Reply...