我像这样动态地进行查询:
$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
。我怎么能这样做?
答案 0 :(得分:3)
也许在你的where子句中使用case语句?
$query = "SELECT u.*
FROM users u
WHERE CASE {$range}
WHEN 'ALL' then TRUE
ELSE date_time > unix_timestamp(DATE_SUB(now()
, INTERVAL 1 {$range}))
END";
答案 1 :(得分:2)
switch ($_GET['range']){
case "week":
$range = "WEEK";
case "month":
$range = "MONTH";
case "year":
$range = "YEAR";
case "ALL":
$range = null;
}
$query = "SELECT u.*
FROM users u
WHERE 1=1 ";
if(!empty($range)) {
$query .= " AND date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 $range))";
}
有条件地添加datetime where子句; WHERE 1=1
永远都是真的。所以下一个条件的结果对最终结果很重要
答案 2 :(得分:1)
我认为亚当的建议是这样的:
$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";
假设使用其他标准进行报告?字符串连接变得混乱的地方。添加&#39; AND&#39;部件之间。完全抑制WHERE关键字?其中表示SQL查询的OOP代码可能很有用。
答案 3 :(得分:0)
首先,您的switch语句没有中断语句,并且不会按预期方式工作。
以下是我建议:
$query = "SELECT u.*
FROM users u";
$range = false;
if (isset($_GET['range'])) {
switch ($_GET['range']){
case "week":
$range = "WEEK";
break;
case "month":
$range = "MONTH";
break;
case "year":
$range = "YEAR";
break;
default:
$range = false;
}
}
if ($range) {
$query .= " WHERE date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 $range))";
}
答案 4 :(得分:0)
我将定义一个具有有效范围的数组,并首先验证用户输入。然后动态地构建查询。
$validRanges = [
'year' => 'YEAR',
'month' => 'MONTH',
'week' => 'WEEK',
'ALL' => null
];
if (isset($_GET['range']) && !isset($validRanges[$_GET['range']])) {
$range = $validRanges[$_GET['range']]);
} else {
// it's up to you, what to do in this case
throw new Exception('Range is not valid or missing');
}
if ($range === null) {
$rangeCondition = '1=1';
} else {
$rangeCondition = "date_time > unix_timestamp(NOW() - INTERVAL 1 $range)";
}
$query = "SELECT u.*
FROM users u
WHERE $rangeCondition";