Php 在构建RESTAPI时,如何处理querystring中参数的动态数量?
当构建一个RESTful api来处理一个可以通过一组动态参数查询的资源时,构建数据库查询的最佳方法是什么 假设资源是一本书,可能的参数是:Php 在构建RESTAPI时,如何处理querystring中参数的动态数量?,php,sql,api,rest,Php,Sql,Api,Rest,当构建一个RESTful api来处理一个可以通过一组动态参数查询的资源时,构建数据库查询的最佳方法是什么 假设资源是一本书,可能的参数是: author, year, publisher, pages, rating 您可以使用任意数量的参数和任意组合构建查询,如: /books?rating=2 或 或 将这组动态参数转换为数据库查询的好方法是什么 创建大量if-else语句,如: if( isset($_GET['rating'] && isset($_GET['aut
author, year, publisher, pages, rating
您可以使用任意数量的参数和任意组合构建查询,如:
/books?rating=2
或
或
将这组动态参数转换为数据库查询的好方法是什么
创建大量if-else语句,如:
if( isset($_GET['rating'] && isset($_GET['author']) ) {
//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
或者是否有其他方法来处理此问题?与其为每个可能的过滤器组合编写单独的查询,不如尝试动态构建单个查询。如果查询字符串上没有请求某些内容,那么您不必担心它 例如(请注意,我自己还没有运行这个,但它至少应该给您一个想法):
非常感谢,这很有道理!
if( isset($_GET['author'] && isset($_GET['year']) && isset($_GET['publisher']) ) {
//Do query based on these parameters here...
}
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....