我正在创建一个非常简单的PHP文件,用于搜索我的SQLite数据库中的表。 我希望它根据2个参数min和max来过滤我的表,但我希望能够指定一个参数,两个甚至都没有。如何将其转换为SQL查询?
<?php
$db = new PDO('sqlite:database.db');
$min = $_GET['min'];
$max = $_GET['max'];
if($min == '') $min = -1;
if($max == '') $max = -1;
$res = $db->prepare('SELECT * FROM Roteiro WHERE ...');
$res->execute(array(...));
$test = $res->fetchAll();
print_r($test);
?>
答案 0 :(得分:1)
您需要动态构建语句:
$db = new PDO('sqlite:database.db');
$min = isset($_GET['min']) && !empty($_GET['min']) ? (integer) $_GET['min'] : null;
$max = isset($_GET['max']) && !empty($_GET['max']) ? (integer) $_GET['max'] : null;
$base = 'SELECT * FROM Roteiro';
$params = array();
if(null != $min && null != $max) {
// im using BETWEEN here just for simplicity int he example,
// but you could (should?) use separate statements with
// typical <,> comparison ops.
$base .= ' WHERE the_column BETWEEN :min AND :max';
$params[':min'] = $min;
$params[':max'] = $max;
} elseif(null !== $max) {
$base .= ' WHERE the_column < :max';
$params[':max'] = $max;
} elseif(null != $min) {
$base .= ' WHERE the_column > :min';
$params[':min'] = $min;
}
$db->prepare($base);
$db->execute($params);
答案 1 :(得分:1)
where (? > a or ? is null)
and (? = foo or ? is null)
-- etc...
诀窍是如果值为null,则满足条件。确保传递类型null,而不是一些空字符串或其他虚假值。
查询优化器应该优化这些额外条件,没有问题,因为它很容易看到它们每行都不会变化。
说出它的等价方式
where (? is not null and ? > a)
and (? is not null and ? = foo)
但我更喜欢第一种方式。
答案 2 :(得分:0)
您需要根据您拥有的信息动态创建查询。
因此,假设您希望通过可选的最小值和可选的最大值来过滤某些表。
SELECT some_row
FROM some_table
WHERE filter_row < [max]
AND filter_row > [min]
一种简单的方法是简单地存储SQL查询中按最大值和最小值过滤的部分,并在需要/定义时将其附加到查询中:
$sql = "SELECT some_row
FROM some_table ";
if (isset($max) && isset($min)){
$sql .= "WHERE filter_row < ?
AND filter_row > ?";
} else if (isset($max) ){
$sql .= "WHERE filter_row < ?";
} else if (isset($min) ){
$sql .= "WHERE filter_row > ?";
}
if ($stmt = $mysqli->prepare($sql)) {
// bind parameters according to the given/available
// parameters and execute
}
我不确定查询是否有效,因为我没有在这里测试它,但这个想法应该是明确的。
这只是一个非常简单的解决方案,随着可选参数列表的增加,会变得非常庞大和丑陋。因此,如果您需要更频繁且需要更多参数,请考虑使用“Query Builder”。