PHP - MySQL删除记录

时间:2012-02-24 02:44:51

标签: php mysql sql database sql-delete

我从数据库中提取记录并创建一个PHP文件,然后在按下“删除”按钮时执行。代码的工作原理是它从数据库中删除记录,但它总是删除数据库中的第一条记录,而不是与表中的请求ID相关的记录。任何帮助都会很棒

表:

<?php

    //3. Perform database query
        $result = mysql_query("SELECT * FROM Request
        WHERE DepID = 'CO'
        AND Status = 'P'", $connection);
        if(!$result){
            die("Database query failed: " . mysql_error());
        }

    //4. Use Returned Data
    while ($row = mysql_fetch_array($result)) {
    $row['ReqID'];  

        echo "<tr>";
        echo "<td class='req' align='center'>".$row['ReqID']."</td>";
        echo "<td class='req' align='center'>".$row['ModTitle']."</td>"; 
        echo "<td class='req' align='center'>".$row['BuildingID']."</td>";
        echo "<td class='req' align='center'>".$row['RoomID']."</td>";
        echo "<td class='req' align='center'>".$row['Priority']."</td>";
        echo "<td class='req' align='center'>".$row['W1']."</td>";
        echo "<td class='req' align='center'>".$row['P1']."</td>";
        echo "<td class='req' align='center'><a href=''><img height='18px' src='images/edit.png'></a></td>";
        echo "<td class='req' align='center'><a href='deletereq.php'><img src='images/exit.png'></a></td>";
        echo "</tr>";




    }
?>

然后这是deletereq.php文件:

<?php require_once("includes/connection.php"); ?>

<?php

    //3. Perform database query
        $result = mysql_query("SELECT * FROM Request
        WHERE DepID = 'CO'
        AND Status = 'P'", $connection);
        if(!$result){
            die("Database query failed: " . mysql_error());
        }

    //4. Use Returned Data
    while ($row = mysql_fetch_array($result)) {
    $row['ReqID'];


$result2 = mysql_query("DELETE FROM Request 
                       WHERE ReqID = {$row['ReqID']} LIMIT 1", $connection);
    if (mysql_affected_rows() == 1) {
                redirect_to("content.php");
            } else {
            //deletion failed
            echo "<h1>Request Deletion Failed.</h1>";
            echo "<p>" . mysql_error() . "</p>";
            echo "<a href=\"request.php\"> Return to request</a>";
        }
        }
?>

<?php mysql_close($connection); ?>

1 个答案:

答案 0 :(得分:2)

在显示页面

echo "<td class='req' align='center'><a href='deletereq.php?id=".$row['ReqID']."'><img src='images/exit.png'></a></td>";

在删除页面上更改查询以使用$ _GET [&#39; id&#39;]

的值

但请注意,根据您的使用情况,您可能真的想从安全等角度了解您的需求。另外一般来说使用GET进行更改并不是一个好主意,最好使用POST然后重定向。点上面的内容会起作用,但是(以及你已经拥有的)足以让你在不小心的情况下对自己造成严重伤害。