使用下拉列表从表中删除

时间:2015-06-11 15:07:37

标签: php html mysql sql-delete

我在从mySQL表中删除时遇到问题。我使用下拉列表选择我需要删除的名称(id)。请帮忙。



         <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>
&#13;
&#13;
&#13;

这是脚本。它在第10行产生错误 - if(isset($_POST['id'])){

&#13;
&#13;
<?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";
    }

}


?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

//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>

然后在提交脚本中

<?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";
    }  

}
?>

我曾经测试过这个,但是如果有的话,只需稍加调整即可,它现在适合你。

我做了什么

  • 鉴于你的名字,所以可以通过delete.php
  • 选择
  • 合并您的产品名称,ID将查询提取到1个查询
  • 取消$ row = $ _POST [&#39; id&#39;]声明:S
  • 在delete.php中检查选择名称(在子弹2中给出)
  • 清除依赖于所选值的ID
  • 删除删除查询

希望这有帮助