在构建处理资源(可以通过一组动态参数进行查询)的 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
或者有其他方法来处理这个问题吗?
最佳答案
您应该尝试动态构建单个查询,而不是为每种可能的过滤器组合编写单独的查询。如果查询字符串中没有请求某些内容,那么您不必担心。
例如(请注意,我自己没有运行过这个,但它至少应该给您一个想法):
$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....
关于php - 构建 REST api 时如何处理查询字符串中参数的动态数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15092373/