仅当存在某个URL时才删除最后一条记录

时间:2019-04-25 09:50:51

标签: php mysql

我的网址是domain.com/abc?orderstatus=cancel

现在,当有人到达此链接时,我想运行一个查询,该查询将从数据库中删除最后一条记录。

这就是我尝试过的:

<?php 

// Code here for the way to connect to database and insert records which works

// Now I added this code so that only if its on the domain.com/abc?orderstatus=cancel url, it will delete the last record.
$orderstatus = $_GET['orderstatus'];

                if($orderstatus == 'cancel') {
                    $sql3 = "delete from table order by CustomerID desc limit 1";
                }


?>

但是,这对我不起作用。我可以知道我做错了什么吗?

ps:我试图切出尽可能多的sql代码,以使其易于阅读。如果我缺少任何信息,请告诉我,我将其放入。

2 个答案:

答案 0 :(得分:1)

如果要基于ORDER BY执行DELETE,则可能必须编写嵌套查询。如果您使用delete from table order by CustomerID desc limit 1

,将会收到SQL语法错误
<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    $orderstatus = $_GET['orderstatus']; // check for sql injections or XSS

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    // sql to delete a record
    $sql = "DELETE FROM {YOUR TABLE_NAME} WHERE {YOUR WHERE CLAUSE} ";

    if ($conn->query($sql) === TRUE) {
        echo "Record deleted successfully";
    } else {
        echo "Error deleting record: " . $conn->error;
    }

    $conn->close();
?>

答案 1 :(得分:1)

如果ID或其他值自动递增,则可以将MAX()用于MySQL。 MAX()将删除您指定的字段上的最高编号。

$sql3 = "DELETE FROM table_name 
         WHERE CustomerID = (SELECT x.id FROM (SELECT MAX(t.CustomerID) AS id FROM table_name t) x)";
//Execute that query
$query3 = mysqli_query($db_conn, $sql3);