Very new to PHP. I am trying to delete database entry with DELETE http request sent from axios in REACT.
function Delete() {
const form = new FormData();
for (var i = 0; i < selected.length; i++) {
form.append(i, selected[i]);
}
console.log(form)
axios.delete(url, form)
navigate(`/`)
}
As you can see here, I iterate over "selected" which is an array and assign keys in the form as numbers. For example first key in form is 1 with first "selected" value and so on. Then comes the PHP code.
header('Access-Control-Allow-Origin: http://localhost:3000');
header("Access-Control-Allow-Methods: GET, POST, DELETE");
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password, 'commerce');
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case "DELETE":
parse_str(file_get_contents("php://input"), $_DELETE);
for ($i = 0; $_DELETE; $i++) {
$sku = $_DELETE[$i];
$delete = $conn->prepare("DELETE FROM baseinfos WHERE sku='$sku'");
$delete->execute();
}
break;
Here I am supposed to get the values of DELETE form, iterate over key values (which are numbers and iteration should work) and delete the corresponding entries in the database. Nothing happens, not even an error is thrown. What should I do???
2
Answers
The first problem is that the signature for axios.delete() is
If you want to send a request body, you need to do so in the config object’s
data
property.Secondly, sending
FormData
in the request body usescontent-type: multipart/form-data
which is not the format parse_str() works with.I would highly recommend using JSON for this instead. Simply send the
selected
array directlyAxios will encode this as JSON and set the appropriate
content-type: application/json
header automatically.To read this on the PHP side, use the following
Note that I’ve used bound SQL query parameters which are a lot safer. You also only need prepare a query statement and bind parameters once. It can then be executed in a loop.
Bodies on
DELETE
requests are not a good idea and generally should be avoided. The purpose of aDELETE
request is to delete the resource identified by the URL you are using.In your case, it looks like you want to define a generic operation that deletes a number of different items.
POST
is more appropriate for this.Servers and clients may drop DELETE request bodies because DELETE request bodies are not intended to be meaningful.
From the latest HTTP specification:
https://www.rfc-editor.org/rfc/rfc9110.html#name-delete