My html:
<td>
<button type="submit" id="delete" name="delete">Verwijderen</button>
</td>
Every record in my table has this button. I intend to delete the record when the respective button is pressed. Everytime I press this button, this error (Notice: Undefined index: product_nr in C:\xampp\htdocs\FESPHP\delete.php on line 3) appears.
The PHP code:
<?php
if (isset($_POST['delete'])) {
$product_nr = mysqli_real_escape_string($con, $_POST['product_nr']);
$deleteq = 'DELETE FROM products WHERE product_nr = "' . $product_nr . '";';
echo $deleteq;
if (!mysqli_connect_errno()){
if (mysqli_query($con, $deleteq)) {
echo "Product deleted";
}
}
var_dump($product_nr);
}
?>
I seem to need help trying to retrieve the product_nr that belongs to the record I want to delete, but I could also be doing alot of other things wrong. Any tips on the other things are also appreciated.
You should place your button in a form:
<td>
<form action="url_to_delete_script.php" method="post">
<input type="hidden" name="product_nr" value="id_of_record"/>
<button type="submit" name="delete">Verwijderen</button>
</form>
</td>
This way, when you submit your form using the button, a post call will be made to the specified script. All information inside the form tag will be sent to the delete_script. So you will find the id of the record in $_POST["product_nr"]
; this is because I have specified a (hidden) field with name "product_nr".
The ID of the record (variable id_of_record
) you can fill in using the PHP script. You are probably using a for loop of some kind to loop over your data anyway.
I don't really know why you do an extra check on $_POST["delete"]
, but if you want to do that, you should another field for this too. Or you can probably also change the URL of the 'action' to url_to_delete_script.php?delete
, but I'm not sure of that.
Other possible solution
To be honest, I hardly ever use this type of record deleting. Because you have a lot of form
tags, and so a lot of duplicated code. I prefer to use jQuery ajax to solve this problem.
My solution in jQuery would have been:
<td>
<button type="button" onclick="removeRecord(id_of_record)">Verwijderen</button>
</td>
<script>
function removeRecord(recordId){
$.post("url_to_delete_script.php",
{ product_nr: recordId },
function(data){
alert("The record with ID " + recordId + " was removed!");
}
);
}
</script>
In this solution you still have to have some kind of table reloading. Because the record is deleted on the server side, but this doesn't reflect in the table immediately.
I prefer this method, but this doesn't mean it's the best solution.
When getting data using post you firstly need to submit it in a form and you need to access it using the elements name, in your case 'delete'. In your case I would recommend adding all of your buttons into a table and going from there.