Ok, this is my HTML form for search:
<form name="search" action="" method="get">
Search for: <input type="text" name="find" /> in
<select name="field">
<option value="author">Author</option>
<option value="papername">Paper name</option>
<option value="coauthors">Co-authors</option>
<option value="abstract">Abstract</option>
<option value="keywords">Keywords</option>
</select>
<input type=submit name=search value="search" />
</form>
And this is my PHP script for fetching results (first couple of conditions, rest are irrelevant, mostly c/p with variable changes):
if($_GET['search'] == "search"){
$loop = "";
$search = !empty($_GET['find']) && ($_GET['find'] != "")?trim($_GET['find']):false;
$field = !empty($_GET['field'])?trim($_GET['field']):false;
if ($search == ""){
echo "Please enter search conditions !";
}
elseif ($search) {
echo "<u>Searched term</u>:"." ".$search."<br />"."<u>In</u>:"." ".$field."<br/>";
if(($field == "Author") || ($search != "")) {
$author_query = mysql_query("SELECT p_authors FROM papers WHERE p_authors LIKE '%$search%'");
$author_output = mysql_num_rows($author_query);
if($author_output > 0){
while ($loop = mysql_fetch_assoc($author_query)) {
print_r($loop);
}
}
else {
echo "No match !";
}
}
elseif(($field == "papername") || ($search != "")){
$author_query = mysql_query("SELECT p_name FROM papers WHERE p_name LIKE '%$search%'");
$author_output = mysql_num_rows($author_query);
if($author_output > 0){
while ($loop = mysql_fetch_assoc($author_query)) {
print_r($loop);
}
}
else {
echo "No match !";
}
}
etc ...
Thing is, i only get output results when option value (Author) is selected (with some keywords in search field), but when i change option value (like papername and others), i get echoed error. Looks like only first if condition (with $field == "Author") is passing through, i cant figure out what is wrong here ? Thx
Strictly answering your question with the information you provided: If you're falling under else
clause, it obviously means your if
clause wasn't fulfilled. In your case, $author_output <= 0
, which lead us to believe 1) your query is returning no results and therefore you must review your table contents, SELECT parameters and etc or 2) your query is returning error and you're not dealing with it as you should.
And as stated in comments, avoid using mysql_
deprecated functions and consider using mysqli_
ones or build PDO
objects.
in your if statement you are using OR(||($search != ""))condition which gets always true as its not null so its executing everytime and other elseif blocks never executes try replacing that with AND(&&) condition as follows
if(($field == "Author") && ($search != "")) {
$author_query = mysql_query("SELECT p_authors FROM papers WHERE p_authors LIKE '%$search%'");
$author_output = mysql_num_rows($author_query);
if($author_output > 0){
while ($loop = mysql_fetch_assoc($author_query)) {
print_r($loop);
}
}
else {
echo "No match !";
}
}