我有一个包含2个选择字段和一个输入的搜索表单,总共3个选项,所以我创建了一些if语句,根据每个字段设置它有自己的查询,但它不能正常工作,都是错误的,结果不对,它与陈述查询混在一起,它没有做对。
以下是搜索表单结果的代码:
$keywords = $_GET["Keywords"];
$location = $_GET['Location'];
$jobtype = $_GET["Category"];
if (isset($location) && empty($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location'
ORDER BY id_job DESC";
}elseif(isset($location) && isset($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' AND
jobType_en = '$jobtype'
ORDER BY id_job DESC";
}elseif(isset($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}
else{
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1'
ORDER BY id_job DESC";
}
$consultaJob = mysql_query($sql_jobs);
答案 0 :(得分:0)
你可能想尝试strlen()而不是isset或empty
否则您必须同时使用isset()
和empty()
empty()
不会生成警告。
strlen()将在NULL和''。
上返回零您可以通过将零值更改为更高的值来设置最小长度。
elseif(strlen($location) > 0 && strlen($jobtype) > 0 && strlen($keywords) > 0 ){
如果提交的值是文本输入,那么您可能还需要修剪:
elseif(strlen(trim($location)) > 0 && strlen(trim($jobtype)) > 0 && strlen(trim($keywords)) > 0 ){
答案 1 :(得分:0)
您需要简化代码:
$sql = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' ";
$order = "ORDER BY id_job DESC";
$where = "";
if( isset( $jobtype ) { $where .= " AND jobType_en = '$jobtype'"; }
if( isset($keywords) { $where .= " AND title_en LIKE '%$keywords%'" };
$sqlx = $sql . $where . $order;
你显然是在早些时候处理$ jobtype和$ keywords。在此处理过程中,您应该设置一些默认值,以便以后处理更容易。
$jobtitle = (isset( $_GET['jobtitle'] ) ) ? $_GET['jobtitle'] : "";
$keywords= (isset( $_GET['keywords'] ) ) ? $_GET['keywords'] : "";
这样你可以使用:
if( $jobtitle != '') { .... }