0

I have an url as domain.com/abc?orderstatus=cancel

Now, when someone reaches this link, I want to run a query that deletes the last record from the database.

So this is what I tried:

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


?>

However, this is not working for me. May I know what am I doing wrong?

ps: I tried to cut out as many sql codes which work so that it makes reading easy. If there is any info that I am missing, please do let me know and I'll put it in.

Gosi
  • 2,004
  • 3
  • 24
  • 36
  • Do you get any error? – the.marolie Apr 25 '19 at 09:52
  • 6
    You don't even execute that sql. How it is supposed to work? – Dorian Mazur Apr 25 '19 at 09:52
  • Have a look at this [post](https://stackoverflow.com/q/12382250/2451726) – Arulkumar Apr 25 '19 at 09:53
  • Assuming that you actually tried to execute the query as well, and not just created a string variable - your server probably doesn’t know what to do with a request for `/abc` on its own, so presumably there’s some URL rewriting going on? If so, have you made sure that the original query string gets passed on in the rewriting process? Otherwise, there might not be a `$_GET['orderstatus']` to begin with. – 04FS Apr 25 '19 at 09:57

2 Answers2

1

If you want to perform DELETE on the basis of ORDER BY then you may have to write nested query. You will get a SQL syntax error if you go with delete from table order by CustomerID desc limit 1

<?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();
?>
Mangesh Sathe
  • 1,987
  • 4
  • 21
  • 40
1

You can use MAX() for MySQL if you have autoincremented on the ID or whatever. MAX() will delete the highest number on the field you specify.

$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);
Budimir Skrtic
  • 419
  • 3
  • 12