Tharindu Rajapaksha
Tharindu Rajapaksha

Reputation: 112

Populating the dropdown with the data on the SQL table?

In my php application i have a dropdown which has to be populated with the data in the food_list table (item name). so I have these code blocks.

<div class="col-sm-8">
 <select name="item_name" class="form-control">
    <option> -- select food item --</option>
     <?php
        $ba = $b->get_all();
        foreach($ba as $item){

            echo "<option>$item->item_name</option>";
        }

    ?>
   </select>

And in my class I've the get_all function as follows.

function get_all(){
    $sql = "SELECT * FROM food_list";
    $ref = $this->db->query($sql);
    while($row=$ref->fetch_array()){
        $b=new foodlist();
        $b->item_name=$row['item_name'];
        $b->unit_price=$row['unit_price'];


        $ar[]=$b;
    }
    return $ar;
}

What can be the reason for not getting the dropdown populated with the relevant data. Note: Database Connection is working properly

food_list(foodID,f_name,f_price)

The data should come from the food_list table f_name column. Please be kind enough to help me. Thank you

Upvotes: 0

Views: 54

Answers (1)

Dan
Dan

Reputation: 5358

To get multiple values with mysqli_result::fetch_array() you nedd to put this into a while-loop:

function get_all(){
     $sql = "SELECT * FROM food_list";
     $ref = $this->db->query($sql);

     while ($row = $ref->fetch_array()) {
          $ar[] = $row;
     }

     return $ar;
}

This will return an array like this:

Array (
     Array (
          [item_name] => Item 1 name
          [unit_price] => 15.00
     )
     Array (
          [item_name] => Item 2 name
          [unit_price] => 20.00
     )
)

Upvotes: 2

Related Questions