简体   繁体   中英

Drop down list with foreach iteration PHP

all

I'm having little problem with : I want to make dynamic drop down list and I write this:

<select name='categoryID' >
    <?php foreach( $categories as $category)?>
    <option value="<?php echo $category['id']?>"> <?php echo $category['name'] ?></option>
</select>

The problem is that foreach doesen't work properly: enters only 1 time. I need to mark that when i dump categories list it shows all items. Any suggestions why is this happen? Is that a right way to make drop down list?

whole code: http://pastebin.com/RE56KQCY

<?php foreach( $categories as $category): ?>
    <option value="<?php echo $category['id']; ?>"> <?php echo $category['name']; ?></option>
<?php endforeach; ?>

you forget to add brackets for foreach

<select name='categoryID' >
    <?php foreach( $categories as $category){?>
    <option value="<?= $category['id']?>"> <?= $category['name'] ?></option>
    <?php } ?>
</select>

You get only one row because you haven't closed your breckets.

Note : I find it really easy to use short_tags , foreach(/.../): endforeach;

PS

I'm not quite sure I have the rights to write this here, but I looked at your code I noticed few problems:

1) You have a connection to DB in the exact file you are using the results. It may be appropriate in your case. Not quite sure. Common practice is to separate your logic and the layer that represents the data you have fetched.

2) You are using mysql_* which is deprecated since PHP 5.5.0 .

This extension is deprecated as of PHP 5.5.0, and will be removed in the future.

Instead of mysql_* you can use PDO or MySQLi .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM