-1

I am having trouble trying to create a delete form in PHP to delete data using the ID given to guests. I am a newbie at this kind of stuff.

Here is the error:

Error: DELETE FROM MyGuests WHERE id= LIMIT 1
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'LIMIT 1' at line 1

Here is my delete.php:

<?php

include_once('mysql.php');

$ins= "DELETE FROM MyGuests WHERE id=$id LIMIT 1";

if ($conn->query($ins) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error: " . $ins . "<br>" . $conn->error;
}

?>

<!DOCTYPE html>
<html>
<body>
<a href='index.php'>Home</a><br>

<h2>Delete User</h2>

<form action="/delete.php" method="post">
  Guest ID:<br>
  <input type="text" name="id" >
  <br><br>
  <input type="submit" value="Submit">
</form> 

</body>
</html>
mmoreno23
  • 7
  • 2
  • 1
    Your are missing to define what $id actually is, so add $id = ... and please read up on https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php and use **prepared statements** – nbk Feb 03 '20 at 20:22

2 Answers2

4

As the easiest fix:

<?php

include_once('mysql.php');

// make sure that form is submitted    
if (isset($_POST['id'])) {

    $ins = "DELETE FROM MyGuests WHERE id=" . $_POST['id'] . " LIMIT 1";
    if ($conn->query($ins) === TRUE) {
        echo "Record deleted successfully";
    } else {
        echo "Error: " . $ins . "<br>" . $conn->error;
    }
}?>

Also note, that passing raw $_POST/$_GET values into query text is insecure. As you don't mention what API you use (PDO or mysqli) I concatenated $_POST value in the query, but you must not. Move to prepared statements asap.

Prepared statements version (I presume you use mysqli according to comparison):

$ins = "DELETE FROM MyGuests WHERE id=? LIMIT 1";
$st = $conn->prepare($ins);
$st->bind_param('i', $_POST['id']);

if ($st->execute() === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error: " . $ins . "<br>" . $conn->error;
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
2

$id is not defined. You're submitting a form so it should probably be: DELETE FROM MyGuests WHERE id={$_POST['id']}

You shouldn't need the LIMIT 1 either. I imagine it would always delete only 1 record.

divil
  • 144
  • 6