My 'else' statement does not seem to be working. I don't understand why.

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.

[php]

<?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; } ?>

[/php]

$result points to a resource so even if empty it will exist instead check for records:

[php]if (count(mysqli_fetch_array($result)) > 0) {[/php]

Worked perfectly.

Many thanks for your help David,

Appreciate the help and the explanation.

Sponsor our Newsletter | Privacy Policy | Terms of Service