0

I am trying to delete a record from my database when I press the submit button (input with type of submit) but this code is not working and I can't figure out why.

Here is the button code:

<input type="submit" value="Delete Selected Weapon" class="mybutton" name="Submit">

Here is the PHP code:

<?php

if(isset($_POST['Submit']))
{
    
    require_once('../connect.php');
    
    $selected = $_POST['deleteweaponname'];
    $sql = "DELETE FROM weapon WHERE weaponname = $selected";
    $result = $connect -> query($sql);

    if(!$result)
    {
        echo "Could not delete record";
    }
    $connect -> close();
}

?>

The $selected variable is supposed to get the value of a select

I don't receive my error message either, when I press the button it just refreshes the site as if there were no PHP code attached to the button.

I also know that my connect.php is working because in another file it works.

I also tried isset($_POST['submit']) but that didn't work either.

I tried putting the code at the end of the file, and now it's in the front of it but neither seems to work.

Pat Rose
  • 13
  • 3
  • You haven't deleteweaponname key from HTML ? Where is coming it ? – Tural Rzaxanov Oct 31 '22 at 09:31
  • 2
    Hmm, does your form use `method="post"`? Basically, your form is missing and we're wondering if the mistake is located there. – KIKO Software Oct 31 '22 at 09:31
  • Try adding an `else` on the `isset` conditional as well. That should tell you which block you get into. This also is open to SQL injections, parameterize your query and use prepared statement. `weaponname` likely is a string so that SQL likely won't work as well. – user3783243 Oct 31 '22 at 09:44
  • 2
    **Warning!** You're _wide open_ to [SQL injection attacks](https://owasp.org/www-community/attacks/SQL_Injection)! Read [how to prevent SQL injection in PHP](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) by using prepared statements with bound parameters instead of injecting variables directly into your queries. If someone would post the value `1 OR 1=1`, _all_ records in that table would be deleted. It would also solve any quoting issues in your query (as others pointed out could be the issue if the column is a string, not an integer) – M. Eriksson Oct 31 '22 at 09:49

1 Answers1

1

The simple solution is quote string value:

$sql = "DELETE FROM weapon WHERE weaponname = '$selected'";

But this solution is open to SQL injection. So best way is using prepared statements:

-- set placeholder for variable
$sql = "DELETE FROM weapon WHERE weaponname = ?";
-- prepare statement
$stmt = $connect->prepare($query);
-- execute statement using variable
$stmt->execute([$selected]);
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39