2

在构建处理资源的 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

还是有其他处理方法?

4

1 回答 1

3

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

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

$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....
于 2013-02-26T15:42:51.973 回答