Rumen Rumen - 3 years ago 183
MySQL Question

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
:

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 ?

Answer Source

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
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download