gpt4 book ai didi

php - 如何组合 2 个不同的过滤器

转载 作者:行者123 更新时间:2023-11-29 09:43:54 26 4
gpt4 key购买 nike

我为日期间隔和不同级别(0,1,2)创建了这个简单的过滤器。到目前为止我有这个代码:

if(isset($_POST['filtersubmit'])){
$datex = str_replace('/', '-', $_POST['firstdate']);
$date1 = date("Y-m-d", strtotime($datex));
$datey = str_replace('/', '-', $_POST['lastdate']);
$date2 = date("Y-m-d", strtotime($datey));
$projects = $_POST['projekt'];



if(isset($date1) && isset($date2)){
$query = mysqli_query($conn, "SELECT * FROM zapasy WHERE datum BETWEEN
'$date1' AND '$date2' ORDER BY id DESC");
}


if($projects == 0){
$query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '0' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
} elseif($projects == 1){
$query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '1' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
} elseif($projects == 2){
$query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '2' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
}
}

现在,如果我只选择这些过滤器之一,它效果很好,但如果我想要间隔过滤器和电平过滤器,它就不起作用。我不太确定该怎么做。我真的很感谢您的帮助。

最佳答案

我会使用类似的方法,使用准备好的语句来保护您免受 SQL 注入(inject)。基本上,我们从每个过滤器中形成 WHERE 子句、参数和参数类型的数组(如果它存在于 $_POST 数组中)。然后将它们内爆到查询中,绑定(bind)参数并执行查询。

if (isset($_POST['filtersubmit'])) {
$params = array();
$paramtypes = array();
$wheres = array();
if (isset($_POST['firstdate'], $_POST['lastdate'])) {
$date1 = date_create_from_format('m/d/Y', $_POST['firstdate']);
$date2 = date_create_from_format('m/d/Y', $_POST['lastdate']);
if (!empty($date1) && !empty($date2)) {
array_push($params, $date1->format('Y-m-d'), $date2->format('Y-m-d'));
array_push($paramtypes, 's', 's');
array_push($wheres, 'datum BETWEEN ? AND ?');
}
}
if (isset($_POST['projekt'])) {
$project = $_POST['projekt'];
if (is_numeric($project) && $project >= 0 && $project <= 2) {
array_push($params, $project);
array_push($paramtypes, 'i');
array_push($wheres, 'projekt = ?');
}
}
$sql = 'SELECT * FROM zapasy';
if (count($wheres)) {
$sql .= ' WHERE ' . implode(' AND ', $wheres);
}
$sql .= ' ORDER BY id DESC';
$stmt = $conn->prepare($sql) or die($conn->error);
if (count($wheres)) {
$stmt->bind_param(implode('', $paramtypes), ...$params);
}
$stmt->execute() or die($stmt->error);
// bind results
$stmt->bind_result(/* variables corresponding to each field in SELECT */);
while ($stmt->fetch()) {
// do something with the data
}
}

关于php - 如何组合 2 个不同的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56055098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com