I have a select field that gets its values from a database table. Not all records in the database have all fields. Some are null. I want my select field to show the name,iata,icao – a combination of these three seperated by a comma. The issue is that some of my fields do not have an icao and some do not have an iaata. Is there a way for me to alter my code such that if there is no icao or iata the comma is ignored.
Please see below:
The code i need to alter is below:
<select name="airport1" class="airport1" id="airport1">
<option selected value="Add">Select Airport</option>
<?php
$mysqli = NEW MYSQLI("localhost", "root", "", "airports");
$resultSet = $mysqli->query("SELECT name,iata,icao
FROM airports order by name ASC;
");
?>
<?php
while ($rows = $resultSet->fetch_assoc()){
$name = $rows['name'];
$iata = $rows['iata'];
$icao = $rows['icao'];
echo "<option value='$name,$iata,$icao'>$name,$iata,$icao</option>";
}
?>
3
Answers
You can check whether
iata
oricao
is null before appending them to the string:OR: You can use
implode
function to join the non-null values with a commaWhat you could do is put those values in a list
then you can remove the "empty" values
and use them to populate what you need to populate, example:
You can use trim to remove trailing commas and a regex to replace if multiple comma consecutive (in this case, only field iata is null):