Cannot print data form mysql table into dropdown

Viewed 35

I have categories table with columns: id and name. I want to display them into dropdown menu. They are stored in the following $categoriesArray:

array (size=6)
  0 => 
    array (size=2)
      'id' => string '1' (length=1)
      'name' => string 'Name 1' (length=12)
  1 => 
    array (size=2)
      'id' => string '2' (length=1)
      'name' => string 'Name 2' (length=14)
  2 => 
    array (size=2)
      'id' => string '3' (length=1)
      'name' => string 'Name 3' (length=10)
  3 => 
    array (size=2)
      'id' => string '4' (length=1)
      'name' => string 'Name 4' (length=14)
  4 => 
    array (size=2)
      'id' => string '5' (length=1)
      'name' => string 'Name 5' (length=20)
  5 => 
    array (size=2)
      'id' => string '6' (length=1)
      'name' => string 'Name 6' (length=14)

I want to display dropdown with option value the ID and option name the name. I've tried the following way:

$sql = "SELECT * FROM categories";
                $result = $conn->query($sql);
                $categoriesArray = array();


                if ($result->num_rows > 0) {
                    echo "<select>";
                    // output data of each row
                    while($row = $result->fetch_assoc()) {
                        array_push($categoriesArray, $row);
                        echo "<option>$categoriesArray[0]['name']</option>";
                    }
                    echo "</select>";
                }

but not sure how to print all the elements. Any ideas ?

2 Answers

You need to concat properly and use id and name accordingly.

echo "<option>$categoriesArray[0]['name']</option>";

should be change to

$i=0;
while($row = $result->fetch_assoc()) {
echo "<option id='".$row[i]['id']."'>".$row[i]['name']."</option>";
i++; // traverse next array
}

You can try like this way also, actually I do it this way.

 //push row data here 
 while ($row = $result->fetch_assoc()) {
        $categoriesArray[$row["id"]]= $row["name"];
 }

 echo "<select>";
 echo "<option selected='selected'>Choose one</option>";

 //make your dropdown here
 foreach($categoriesArray as $id=>$name) {
    echo "<option value=$id>$name</option>";
 }
 echo "</select>";
Related