I am trying to fill a combo box from a custom table in WordPress. print_r(array_values($cellco_options))
returns the expected array of 15 items.
My foreach
statement is a problem. If I echo the variables the combobox will not fill with items. If I remove the echo the combox fills with 15 items but they are blank.
Questions:
Why is echo not allowing the box to fill?
How can I fill my box with items I can see, is echo the wrong method in this case?
<?php
global $wpdb;
$cellco_options=$wpdb->get_results("SELECT `id`, `cellco` FROM `ea_cellcarrier` WHERE 1");
?>
<p>
<label for="cell_carrier<?php $template->the_instance(); ?>"><?php _e( 'Cell Carrier', 'theme-my-login' ) ?></label>
<select type="text" name="cell_carrier" id="cell_carrier<?php $template->the_instance(); ?>" tabindex="20" />
<option disabled selected value=""> -- select -- </option>
<?php
foreach ($cellco_options as $id => $cellco) { ?>
<option value= "<?php echo $id; ?>"><?php echo $cellco; ?></option>
<?php }
?>
</select>
</p>
Your select html tag is closed at the end of the line.
And you can use php alternative syntax for the code.
Thank you miken32, I tried your tip and still had the blank spaces, however, your tip led to the following solution that works:
Your database results are not indexed by
id
so your foreach loop was not getting what you expected.Also note the alternative syntax I used with the
foreach()
loop. It can be much easier to read in cases like this where you’re mixing your PHP with HTML.