【问题标题】:Delete Items API for iOS App (calls to PHP for the API call)Delete Items API for iOS App(为 API 调用调用 PHP)
【发布时间】:2014-06-02 04:30:16
【问题描述】:

这是我们目前的设置。我们有一个 iOS 应用程序对我的 PHP 脚本进行 API 调用,该脚本处理请求并通过 PDO 和 MySQL 查询数据库。因此,在这种情况下,有一个 update_items.php API,iOS 应用程序将参数值发送到该 API,并且根据用户是更新项目还是删除项目,API 会相应地处理它并多次查询数据库(全部在一个请求中) )。

这是我的困境。我有更新位工作,但如何使用相同的更新 API 通过 POST 请求删除项目?我的 iOS 开发人员想出的一个快速补救措施是,如果用户滑动删除一个项目,他会将项目的名称发送为“DELETE”或类似的内容。这将启动数据库记录的删除查询。我不喜欢这样,因为任何人都可以弄清楚这一点并利用该系统。例如,在编辑一个项目时,我所要做的就是在 DELETE 中输入项目的名称,API 会像处理删除请求一样处理它。必须有更好的方法,我将不胜感激任何建议。下面是我当前处理 API 调用的 PHP 代码。然而,我的建议是在用户单击“完成”以编辑他们的项目页面后同时发送两个 API 调用。如果用户更新一个项目,则一个 update.php,如果用户决定删除一个项目,另一个 delete.php。

// 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();
}

【问题讨论】:

    标签: php ios api


    【解决方案1】:

    REST 的答案是不要使用 POST 请求,使用单独的 DELETE 请求。

    【讨论】:

    • 我花了将近两个小时研究 DELETE 请求,在我看来它已经过时了,我仍然不确定它的使用要求是什么。描述和用法似乎含糊不清,但它是如何工作的呢?我去了 php.net 和其他 REST 资源,但似乎仍然无法阅读清晰、直接的答案。例如,POST 接收传递的参数并将它们插入到 INSERT SQL 查询的 Prepared PDO 语句中...... DELETE 如何用于 DELETE SQL 查询?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2011-04-12
    • 1970-01-01
    相关资源
    最近更新 更多