無法將mysql表中的數據打印到下拉列表中

[英]Cannot print data form mysql table into dropdown


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

我有帶有列的分類表:id和名稱。我想把它們顯示到下拉菜單中。它們存儲在以下$categories數組中:

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:

我想顯示下拉菜單的選項值ID和選項名名稱。我試過以下方法:

$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 个解决方案

#1


4  

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

您需要正確地使用id和名稱。

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
}

#2


2  

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>";

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/09/30/72a347d4a7be6ad0899b1d298f4bee60.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com