php - 构建 REST api 时如何处理查询字符串中参数的动态数量?

标签 php sql api rest

在构建处理资源(可以通过一组动态参数进行查询)的 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/

相关文章:

javascript - 发送后出现错误 "can' t 设置 header ”

php - MYSQL如何找到字段的最大值?

javascript - 带有 json 格式数据的 AJAX 脚本不起作用

php - 数据库之间的 Blob 编码差异

MySQL 仅当列中的行重复时才选择条件

json - 在 Coldfusion 中的 api Web 服务中以 json 格式发送纯文本

php - 如何从 foreach(PHP) 中只获得一个结果

java - 在列上使用别名的查询会出错

python - 如何使用 SQLAlchemy 执行嵌套查询中存在的位置?

ruby-on-rails-3 - 检查/取消选中喜欢/不喜欢喜欢/不喜欢资源的 REST 方式