I'm trying to execute a delete query, but it doesn't work.
The thing is that I echoed the id, and it was the same as the id in the database. I execute the query in MySQL, and it works also. The last thing is that the try block is executed and the success message is shown, but the data wasn't deleted from the database.
if (isset($_POST['delete'])){
try {
$p_id = $_POST['product_id'];
$p_id = filter_var($p_id, FILTER_SANITIZE_STRING);
var_dump($p_id);
$delete_product = $conn->prepare("DELETE FROM `products` WHERE `id` = ?");
$delete_product->execute([$p_id]);
$success_msg[] = "product deleted successfully";
}catch (PDOException $err) {
echo $err->getMessage();
}
}
How I saved the ID:
<input type="hidden" name="product_id" value="<? $fetch_product['id'];?>">
How I checked the ID:
<button type="submit" name ="delete" class="btn" onClick="return confirm('delete this product<?= $fetch_product['id'];?>"');"
>delete</button>
Answers
It looks like the issue might be with how you're retrieving the product ID from the form. In your hidden input field, you're missing the PHP echo tag to output the value of $fetch_product['id']
. Without the echo tag, the value won't be included in the HTML output, resulting in an empty or uninitialized product_id
field when the form is submitted.
To fix this, make sure to include the echo tag when outputting the product ID in the hidden input field:
<input type="hidden" name="product_id" value="<?= $fetch_product['id']; ?>">
With this change, the product ID should be properly passed to the PHP script when the form is submitted, allowing the delete query to execute successfully.