Why isn't my 'else' statement working.

Hi all,
I've created a basic search form with 2 inputs from drop down menus which will return results to a results page. My two input fields in the search form are 'language' and 'prefecture'.

My code php below  displays the correct results when there are results in the database. However, when there are no results in the database which match the search criteria,  the code doesn't do what I hoped it would do (i.e. redirect and disconnect). All that happens is that no results are displayed in my results page.  

Any idea what I am doing wrong? Many thanks for reading.



$language = $_POST['language'];
$prefecture = $_POST['prefecture'];

$sql = "SELECT * FROM teacher_table WHERE language = '".$language."' AND prefecture = '".$prefecture."'";
$result =mysqli_query($db_connection, $sql);

 if($result) { 
    // Results
	While ($rows = mysqli_fetch_array($result)){
	echo $rows['firstname'];
	echo $rows['language'];
	echo $rows['prefecture'];

	else {
    // No Results
    redirect_to ('no_results.php');


Open in new window

AdamTrying to learn phpAsked:
Who is Participating?
Julian HansenCommented:
Because your if is working off $result
Returns false only if the query failed - not when there are no results. No results is a valid result and so the return from mysqli_query will be non-false

You need to check

if ( mysqli_num_rows ($result ) > 0) {
    // output here
else {
   // this is where you do the else part

Open in new window

AdamTrying to learn phpAuthor Commented:
Ah, I see.

Many thanks Julian for the solution and a clear explanation.

Julian HansenCommented:
You are welcome.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.