Phantom option lines in select input

I am having an issue with dynamically creating a select input for a form. I have 2 select input fields. If I create either one without the other, no problem. However, when I have both select inputs active in the form, the 2nd one loads with a bunch of blank lines ahead of the actual options.

Here is the PHP script that creates the select fields.

<?php

include 'host_setup.php';
include 'link_to_database.php';

// Incident types
$sql = 'SELECT * FROM tbl_incident_type';
$result1 = mysqli_query($link, $sql);

if (!$result1)
{
    $output = 'Error fetching database records: '. mysqli_error($link);
    include 'output.html.php';
    exit();
}
// Records retrieved.  Put them in an array
while ($row = mysqli_fetch_array($result1))
{
	$retrieved[] = array('ID'=>$row['ID'], 'inc_type'=>$row['inc_type']);
}

// Put the results in a select statement
$fld_inc_type = '<select class="form-control" name="incType" id="incType">';
  foreach ($retrieved as $entry){
    $fld_inc_type .= '<option value = '.$entry['ID'].'>'.$entry['inc_type'].'</option>';
  };
$fld_inc_type .= '</select>';
mysqli_free_result($result1);


// Alarm types
$sql = 'SELECT * FROM tbl_alarmType';
$result2 = mysqli_query($link, $sql);

if (!$result2)
{
    $output = 'Error fetching database records: '. mysqli_error($link);
    include 'output.html.php';
    exit();
}
// Records retrieved.  Put them in an array
while ($row = mysqli_fetch_array($result2))
{
	$retrieved[] = array('ID'=>$row['ID'], 'alarmType'=>$row['alarmType']);
}

// Put the results in a select statement
$fld_alarm_type = '<select class="form-control" name="alarmType" id="alarmType">';
  foreach ($retrieved as $entry){
    $fld_alarm_type .= '<option value = '.$entry['ID'].'>'.$entry['alarmType'].'</option>';
  };
$fld_alarm_type .= '</select>';
mysqli_free_result($result2);

?>

In the form, I insert a quick line of PHP and echo the select variable in its appropriate location. What I get with the first one loaded in the form is a correct select list. The 2nd one loaded will have a bunch of blank lines, then the select options. Coincidentally (not I’m sure), the number of blank lines are equal to the number of select options in the other select input field.

Any assistance would be greatly appreciated.

Hint: How many rows are you getting blanks, and how does that relate to the first box?

Answer: You’re reusing $retrieved without emptying the array from the first set of results. The blanks are all of your incident types, for which the alarmtype is not set.

The number of blank rows equals the number of options in the previous select. I will try NOT using $retrieved for both.

1 Like

Bingo! I changed $retrieved and it works perfectly.

Thanks.