user3865463
user3865463

Reputation: 103

Using foreach with mysqli_fetch_assoc

I have a mysql table with two columns; id and type. I'm trying to retrieve those values to use in a select list of values (aka drop down list). Outside of my html, this php works perfectly:

$sql = "SELECT * FROM `usertype`";
$query = mysqli_query($con, $sql);
while ($type_lov = mysqli_fetch_assoc($query)) {
echo '<pre>', print_r($type_lov,true), '</pre>';
};

Output from php above:

Array ( [id] => 1 [type] => System Admin ) 
Array ( [id] => 2 [type] => System Admin2 ) 
Array ( [id] => 3 [type] => System Admin3 ) 
Array ( [id] => 4 [type] => Account Admin ) 
Array ( [id] => 5 [type] => Account User )

To get it into the SELECT / OPTIONS tags, I attempted several things unsuccessfully. The two attempts that made the most sense to me (but that did not work) were:

<!--ATTEMPT 1-->    
<select>
    <?php while ($type_lov = mysqli_fetch_assoc($query)) {
        foreach ($type_lov as $id=>$type) { ?>
            <option value="<?php echo $id; ?>"><?php echo $type; ?></option>
        <?php };
    }; ?>
</select>

<!--ATTEMPT 2-->
<select>
    <?php foreach ($type_lov = mysqli_fetch_assoc($query) as $id=>$type) { ?>
        <option value="<?php echo $id; ?>"><?php echo $type; ?></option>
    <?php }; ?>
</select>

Neither worked. What is the proper way to go about this?

Upvotes: 1

Views: 8431

Answers (2)

Kep
Kep

Reputation: 5857

You should read up on mysqli_fetch_assoc. It returns it's data as an associative array, meaning your table columns are used as indices for the array.

Furthermore, why are you coupling while with foreach in your first example? What's the thought process that you went on?

Anyway, this should help you on your journey:

<select>
    <?php
        while (($data = mysqli_fetch_assoc($query)))
        {
            echo '<option value="' . $data['id'] . '">' . htmlspecialchars($data['type']) . '</option>';
        }
    ?>
</select>

Upvotes: 2

Raghav
Raghav

Reputation: 1

There is a difference between While and foreach.

Have to use while when you need to loop based on a condition that may change or when fetching data in a sequential manner (e.g., from a database).

Use foreach when iterating over arrays or objects where you want to access each element without the need for explicit index management.

Upvotes: -1

Related Questions