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.

Regards,
Adam

<?php

$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');
    db_disconnect($db_connection);
    exit;
    }

?>

Open in new window

AdamTrying to learn phpAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Because your if is working off $result
mysqli_query
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

3

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AdamTrying to learn phpAuthor Commented:
Ah, I see.

Many thanks Julian for the solution and a clear explanation.

Cheers
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.