Jared Jared - 1 month ago 6
MySQL Question

Search query doesn't return desired results

I have kind of advanced search function. All works fine except one

AND LIKE ...
.
There are two options
A
or
A, *AB
. I want when I choose
A
to return results only which are
A
in database and when I choose
A, *AB
to return results which are only
A, *AB
.

What is happening now is that when I choose
B, *AB
it returns results which for both

A
A, *AB


My form is with action
get
. This is my query

$couGe=($ge == "None") ? "" : "AND c.ge LIKE '".substr($ge, 0, 2)."%'";
$active = ($this->showCouCancelled) ? "AND (c.active=1 OR c.active=7)" : "";
$active = ($this->hideCouActive) ? "AND (c.active=1 OR c.active=3 OR c.active=4 OR c.active=7)" : "";
$couName = ($cName) ? "AND course_title LIKE '%$cName%'" : "";
$couDept = ($cDept) ? "AND s.dept='$cDeptArray[0]' AND s.dept_code='$cDeptArray[1]'" : "";

$iRes = _SQLQuery("
SELECT DISTINCT c.id,s.dept,s.dept_code,c.course_title,c.active,s.year,s.sem,c.ge,c.course_type
FROM courses AS c, sections AS s, teachers as t, tea_sec_rel as tsr
WHERE s.course_id_rel=c.id AND $curYr $curSem $active $couName $couDept $psSearch $couGe
ORDER BY s.dept,s.dept_code");


The html select option menu has

<select name="ge" id="ge">
<option value="None">All</option>
<option value="A">A</option>
<option value="A, *AB">A, *AB</option>
</select>


On the query this is the line which take
ge


$couGe=($ge == "None") ? "" : "AND c.ge LIKE '".substr($ge, 0, 2)."%'";


When I
var_dump($_GET['ge']
I see that I get what I choose. I'm very confused and any help is appreciated.

Answer

You need to change a bit your query and the way you assign $couGe where you took selected ge. Please try this way

$couGe=($ge == "None") ? "" : "'".substr($ge, 0, 2)."'";
$active = ($this->showCouCancelled) ? "AND (c.active=1 OR c.active=7)" : "";
$active = ($this->hideCouActive) ? "AND (c.active=1 OR c.active=3 OR c.active=4 OR c.active=7)" : "";
$couName = ($cName) ? "AND course_title LIKE '%$cName%'" : "";
$couDept = ($cDept) ? "AND s.dept='$cDeptArray[0]' AND s.dept_code='$cDeptArray[1]'" : "";

$iRes = _SQLQuery("
                SELECT DISTINCT c.id,s.dept,s.dept_code,c.course_title,c.active,s.year,s.sem,c.ge,c.course_type
                FROM courses AS c, sections AS s, teachers as t, tea_sec_rel as tsr
                WHERE s.course_id_rel=c.id AND $curYr $curSem $active $couName $couDept $psSearch $couTea AND c.ge LIKE $couGe
                ORDER BY s.dept,s.dept_code");
Comments