Here is our current set up. We have an iOS app that makes API calls to my PHP script which handles the request and queries a database via PDO and MySQL. So in this case there is an update_items.php API that the iOS app sends parameter values to and based on whether the user is updating an item or deleting an item, the API handles it accordingly and queries the database multiple times (all in one request).
Here's my predicament. I have the update bit working, but how can I use the same update API to delete an item via POST request? A quick remedy my iOS developer came up with is that if a user swipes to delete an item, he sends the item's name as "DELETE" or something along those lines. This initiates a delete query for the database record. I don't like this because anyone could figure this out and exploit the system. For example, while editing an item all I have to do is enter in DELETE for the item's name and the API would process it the same as a delete request. There has to be a better way and I would appreciate any suggestions. Below is my current PHP code that handles the API call. My suggestion, however, was to simultaneously send two API calls after a user clicks DONE for editing their item page. One to update.php if the user updates an item and another delete.php if a user decides to delete an item.
// now check for updating/deleting ingredients for the menu item
if( isset($the_request['id']) ) {
/*
iterate through avalialable values because there could be multiple ingredient ids involved. handle it.
*/
for( $i=0;$i<count($the_request['id']);$i++ ) {
// the queries. check if ingredient is being deleted or not via passed paramater value
switch($the_request['name'][$i]) {
case 'DELETE':
// assign passed parameter for delete query
$params = array(
':id' => $the_request['id'][$i]
);
// the query
$query = 'DELETE FROM TABLE WHERE id = :id';
break;
default:
// assign passed parameters for query
$params = array(
':name' => $the_request['name'][$i],
':price' => $the_request['price'][$i]
);
// Remove the empty values
$params = array_filter($params, function($param) { return !empty($param); });
// Build an array of SET parameters
$set = array_map(function($key) {
return sprintf('%s = %s', substr($key, 1), $key);
}, array_keys($params));
// don't forget the id
$params[':id'] = $the_request['id'][$i];
// the query
$query = sprintf('UPDATE TABLE SET %s WHERE id = :id', implode(', ', $set));
}
// prepare statement
if( $ingStmt = $dbh->prepare($query) ) {
$ingStmt->execute($params);
} else {
echo json_encode(array('error' => $dbh->errorInfo().__LINE__));
}
}
$ingStmt->closeCursor();
}
The REST answer is don't use a POST request, use a separate DELETE request.