Reputation: 13
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.
Upvotes: 0
Views: 75
Reputation: 10163
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]);
Upvotes: 1