我在下面的代码段中,从下拉列表用户选择中提取$filter_xx
值。
我正在尝试使用用户选择通过下拉列表选择查询数据库来查询mySQL数据库。
您将看到有4个$filter_xx
变量,并且在给定实例中设置了多少变量是完全随机的。
问题是当我在查询中使用&&
时,它检查所有四个参数是否为真,然后抛出并输出。 (我知道&&
假设以这种方式工作!)。我尝试用&&
替换所有||
运算符,但没有运气。
如何仅使用用户选择的选项搜索数据库?
if(isset($filter_brand) || isset($filter_year) || isset($filter_month) || isset($filter_status))
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand' && startyear='$filter_year' && startmonth='$filter_month' && status='$filter_status' ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
答案 0 :(得分:1)
如果有多个值必须以类似方式工作,请将数组与循环一起使用。我想,你正在使用mysqli,如果需要,可以更改PDO的引用。
$mysqli = new mysqli("localhost", "user", "pass", "test");
//...
//SQL attr name => name of POST parameter
$filter = array('brand' => 'brand', 'startyear' => 'year',
'startmonth' => 'month', 'status' => 'status');
//here we'll store SQL conditions
$sql_filter = array();
foreach($filter as $key => $value)
{
if (isset($_POST[$value]))
{
//use your library function to quote the variable before using it in SQL
$sql_filter[] = $key . '="'. $mysqli->escape_string($_POST[$value]) . '"';
}
}
$query = "SELECT * FROM targets ";
if(isset($sql_filter[0]))
{
$query .= 'WHERE ' . implode(' AND ', $sql_filter) . ' ';
}
$query .= 'ORDER BY createdon DESC';
答案 1 :(得分:0)
试试这个
$join = "";
//TAKE ONE BLANK VARIBLE THAT JOIN IF VALUE IS SET
if(isset($filter_brand)){
//IF VALUE ISSET THAN IT ADDED TO QUERY
$join .= " AND brand='$filter_brand'";
}
if(isset($filter_year){
$join .= " AND startyear='$filter_year'";
}
$query = "SELECT * FROM targets WHERE id != '' $join ORDER BY createdon DESC";
答案 2 :(得分:0)
试试这个:
$query = "SELECT * FROM targets WHERE 1 ";
$query = isset($filter_brand) ? $query . " AND brand = '".$filter_brand."'" : $query;
$query = isset($filter_year) ? $query . " AND startyear = '".$filter_year."'" : $query;
$query = isset($filter_month) ? $query . " AND startmonth = '".$filter_month."'" : $query;
$query = isset($filter_status) ? $query . " AND status = '".$filter_status."'" : $query;
$query .= " ORDER BY createdon DESC";
答案 3 :(得分:0)
您可以这样做:
ᴀᴀ ʙᴄ ᴅᴀ