php - MySQL 中的动态搜索查询

标签 php mysql node.js database knex.js

这里是项目安装:
1. Nodejs服务器端环境
2. MySQL数据库(带Knexjs查询生成器)
3. 数据库中的 'locations' 表,包含 'country'、'city'、'category'、'working_hours' 等字段。
4. 用户可以选择所有这些值并提交搜索的表单输入。当用户什么都不选择时,它默认为“全部”。我需要过滤数据库并选择与用户搜索输入对应的行。

我试着做这样的事情:

knex('locations').where({
   country: countryInput,
   city: cityInput,
   category: categoryInput,
   working_hours: hoursInput
   })
   .then(function(rows) {.....})
   .catch(function(err) {.....});

如果用户选择了所有输入字段,这会很好用,如果用户只选择其中的几个而其他设置为“全部”怎么办?如何实现?

提前致谢!

最佳答案

这是很常见的解决方案:

let query = knex('locations');

if (countryInput) {
  query = query.where('country', countryInput);
}

if (cityInput) {
  query = query.where('city', cityInput);
}

if (categoryInput) {
  query = query.where('category', categoryInput);
}

if (hoursInput) {
  query = query.where('working_hours', hoursInput);
}

query
  .then(function(rows) {.....})
  .catch(function(err) {.....});

关于php - MySQL 中的动态搜索查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45005753/

相关文章:

java - 以编程方式配置 Hibernate - 无法创建请求的服务 [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

mysql - 从两个表中选择并总是从一个表中返回

php - 在Mysql表中搜索带空格或不带空格的关键字

node.js - Joi 验证和模式

javascript - hottowel undefined 不是一个函数

php - javascript 和 PHP 变量传递

javascript - 单击更改 url 而不重新加载

php - 按 id 对结果进行分组的 MySQL SELECT 语句?

node.js - 使用 Homebrew 软件升级 npm

php - 通过检查选项按钮进行排序 PHP MYSQL