admin

如何在动态查询中模拟WHERE 1?

sql

我正在像这样动态查询:

$query = "SELECT u.*
          FROM users u
          WHERE date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 $range))";

$range包含这样的单词:

switch ($_GET['range']){
   case "week":
      $range = "WEEK";
   case "month":
      $range = "MONTH";
   case "year":
      $range = "YEAR";
   case "ALL":
      $range = <I don't know what should I put here to get the expected result>;
}

就像我在上面说过的,我想设置一些$range值作为值使WHERE子句类似WHERE 1。我怎样才能做到这一点?


阅读 178

收藏
2021-07-01

共1个答案

admin

我认为亚当的建议是这样的:

$where = '';

switch ($_GET['range']) {

    case "week":
       $where = "date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 WEEK))":
        break;

    case "month":
       $where = "date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 MONTH))":
        break;

    case "year":
       $where = "date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 YEAR))":
        break;

    default:
        $where = '';
}

$query = "SELECT u.* FROM users u WHERE $where";

假设使用其他条件进行报告?字符串连接变得混乱的地方。在零件之间添加“与”。完全禁止使用WHERE关键字吗?其中表示SQL查询的OOP代码可能很有用。

2021-07-01