Unable to print mysql data table in dropdown menu

I have a category table with columns: id and name. I want to display them in the dropdown menu. They are saved as follows $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 a dropdown menu with the value ID parameter and the option name name. I 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?

+4
source share
2 answers

You need to perform the correct execution and use idand nameaccordingly.

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

should be changed to

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

You can also try in this way, in fact 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>";
+2
source

Source: https://habr.com/ru/post/1686685/


All Articles