HTML按钮通过post方法调用php代码,但SQL查询不起作用

I'm trying to build an html table with a "remove" button on each row that once pressed, calls an sql query with the item ID as parameter, that removes an item from the "basket" table on my DB. As for now, when the button is pressed nothing happens. I think the problem should be with the parameter that I pass because when I change the query to remove specific ID when a button pressed, it does work well.

This is part of my code: (if you need the entire file I will supply the rest of the code).

html part:

    <td>
      <form name="myForm" method="post" action="<?php $_SERVER['PHP_SELF'];?>" >
        <input type="submit" class="css3button" value="remove"  / > </td>
        <input type="hidden" name="Id" id="Id" value="<?php echo $Id; ?>" />
        </form>
     </td>

php part:

if(isset($_POST['myForm'])){
    $removal = sprintf("DELETE FROM Basket WHERE Id='%s'" ,mysql_real_escape_string($Id));
    $remove_result = mysql_query($removal);

    if (!$remove_result ) {
        echo "DB Error, could not query the database
";
        echo 'MySQL Error: ' . mysql_error();
        exit;
    }
}

Put " to end your string in the argument of sprintf.

I see a few problems here:

  1. $_POST['myForm'] will never be present, only $_POST['Id'] will be.

  2. Unless you defined $Id that we can't see, that will be null so use $_POST['Id'] instead.

  3. Probably just a typo in the question but the string with the query is not closed.

  4. In the form HTML you use <?php echo $Id; ?>, so again you need to verify that $Id holds some data and is not null/undefined.

Try:

if(isset($_POST['Id'])){
    $removal = sprintf("DELETE FROM Basket WHERE Id='%s'" ,mysql_real_escape_string($_POST['Id']));
    $remove_result = mysql_query($removal);

    if (!$remove_result ) {
        echo "DB Error, could not query the database
";
        echo 'MySQL Error: ' . mysql_error();
        exit;
    }
}

Your code would not be considered insecure but you really shoud ditch the mysql_* library in favor of PDO or MySQLi and use prepared statements where user input is needed in the query.