【问题标题】:How to handle dynamic number of parameters in querystring when building REST api?构建REST api时如何处理查询字符串中的动态参数数量?
【发布时间】:2013-02-26 23:59:58
【问题描述】:

在构建处理资源的 RESTful api 时,可以通过一组动态参数进行查询,构建对数据库的查询的最佳方式是什么?

假设资源是一本书,可能的参数是:

author, year, publisher, pages, rating

您可以使用任意数量的参数和任意组合构建查询,例如:

/books?rating=2

/books?author=james&year=2001&rating=4

/books?year=2010&publisher=greatbooks&pages=100&rating=5

将这组动态参数转换为数据库查询的好方法是什么?

创建很多 if else 语句,例如:

if( isset($_GET['rating'] && isset($_GET['author']) ) {

    //Do query based on these parameters here...

}

if( isset($_GET['author'] && isset($_GET['year']) && isset($_GET['publisher']) ) {

    //Do query based on these parameters here...

}

等等等等等等……

或者设置所有变量,然后在查询中使用 LIKE 而不是 '=',如下所示:

if(!empty($_GET['author'])) {
    $author = $_GET['author'];
} else {
    $author = '%';
}

然后

SELECT * FROM books WHERE author LIKE $author ... and so on

或者有什么其他的方法可以解决这个问题?

【问题讨论】:

    标签: php sql api rest


    【解决方案1】:

    您应该尝试动态构建单个查询,而不是为每个可能的过滤器组合编写单独的查询。如果查询字符串上没有请求某些内容,那么您不必担心。

    例如(请注意,我自己没有运行这个,但它至少应该给你一个想法):

    $sql = 'SELECT * FROM books';
    
    // build an array of WHERE clauses depending on what is in the query string
    $clauses = array();
    $filters = array('author', 'year', 'publisher', 'pages', 'rating');
    foreach ($filters as $filter) {
      if (array_key_exists($filter, $_GET) {
        $clauses[] = sprintf("%s = '%s'", $filter, mysqli_real_escape_string($_GET[$filter]);
      }
    }
    
    // if there are clauses, add them to the query
    if (!empty($clauses)) {
      $sql .= sprintf(' WHERE %s', implode(' AND ', $clauses));
    }
    
    // Run the query....
    

    【讨论】:

    • 非常感谢,这很有道理!
    猜你喜欢
    • 1970-01-01
    • 2013-04-10
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    相关资源
    最近更新 更多