For loop sometimes populates but not all the the time

I have the following PHP code:

<select name="location" id="shortdescription">

	<?php


$query = "SELECT loc_short_desc FROM location_surface_type";
$results=mysqli_query($link, $query);
 foreach ($results as $loc_short_desc){
                ?>
                        <option value="<?php echo $loc_short_desc["loc_short_desc"];?>"><?php echo $loc_short_desc["loc_short_desc"];?></option>
                <?php
                    }
?>
</select>

But when on my test host-(WAMP), my for loop works out perfectly. But when I am using my actual host-(Fatcow.com), it doesn’t display anything except for the select box. Do you have any suggestions on how to possibly fix this issue?

Either your connection or query statement is probably failing, but you have no error handling, so the code just continues to run past the point of the error and you end up with an empty select /select menu, and also several php errors.

  1. You need to ALWAYS have php’s error_reporting set to E_ALL, in the php.ini on your system and when learning, developing, and debugging code/queries, set display_errors to ON, and when on a live/public server, set display_errors to OFF and set log_errors to on. This will get php to help you by either displaying or logging all the errors it detects.
  2. You need to ALWAYS have error handling for any statement(s) that can fail. The easiest way of adding error handling for database statements is to enable exceptions for errors and in most cases let php catch and handle the exception, where it will use its error related settings to control what happens with the actual error information (database errors will get displayed or logged the same as php errors.)

To enable exceptions for errors for the mysqli extension, add the following line of code before the point where you make the database connection -

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service