Deleting from table using drop down list

1.6k views Asked by At

I have a problem with deleting from mySQL table. I'm using drop down list to select which name (id) I need to delete. Please help.

         <h1><a href="#" class = "2">Delete product</a></h1>
         <form method="post" action = "Delete.php">
         <div class="Delete">
         <select>

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

    $query = mysql_query("SELECT name FROM `products`");
    $id = mysql_query("SELECT id FROM `products`");

    while($row=mysql_fetch_array($query)){

    echo "<option value='". $row = $_POST['id']."'>".$row['name'].'</option>';
}

?>
</select>

     <input type="submit" name="" value="Delete">


 </form>
         </div>

And this is script. It makes error on line 10 - if(isset($_POST['id'])){

<?php


if($_SERVER["REQUEST_METHOD"] == "POST"){

    require('connect.php');

    $id = mysql_query("SELECT id FROM `products`");

    if(isset($_POST['id'])){

    $id = mysql_real_escape_string($_POST['id']);



        $query2 = "DELETE FROM `products` WHERE id = '$id'";

        $result=mysql_query($query2);


        if($result){
            header("Location: tools.php");
            exit;
        }
        else{
            echo"ERROR";
        }

    }
    else{
        echo"Bad ID";
    }

}


?>

1

There are 1 answers

0
JParkinson1991 On

Try something like this

//Give select a name so delete.php can hook into it
<select name="product_id">
<?php
require('connect.php');

//Merge your 2 queries into one
$query = mysql_query("SELECT id, name FROM products");

//Fix value fetching in your while loop
while($row=mysql_fetch_array($query)){
    echo "<option value='". $row['id']."'>".$row['name'].'</option>';
}

?>
</select>

Then in your submit script

<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){

    require('connect.php');

    //Look for select name
    if(isset($_POST['product_id'])){

        //Get ID from select value
        $id = mysql_real_escape_string($_POST['product_id']);

        $query = "DELETE FROM products WHERE id = '$id'";

        $result = mysql_query($query);

        if($result){
           header("Location: tools.php");
           exit;
        }
        else{
           echo"ERROR";
        }

    }
    else{
        echo"Bad ID";
    }  

}
?>

I havnt tested this but with minor tweaking if any, it should now work for you.

What i have done

  • Given your a name so it can be picked up by delete.php
  • Merged your product name, id fetch queries into 1 query
  • Killed off that $row = $_POST['id'] statement :S
  • In delete.php checked for the select name (given in bullet 2)
  • Clean up id depeneding on selected value
  • Ran delete query

Hope this helps