phphtmlmysqlselectecho

How should I create a dynamic list of <select> options with php/mysql?


I am trying to create a <select> list that has one option for each item of stationery, but the select options return empty in the following code. What have I done wrong/how could I fix this?

the code I tried to use ($dbc is a connect query, which I verified works).

<?php
if (!isset($choice))
{
  echo'
  <form action="'.$self.'" method="post">
   I would like to order:       
   <select name="choice" id="choice">';
            
   #Create a list of all item in db, make each of them an option. 
   $sql2="SELECT name FROM stationery";
   $result2=mysqli_query($dbc, $sql2) or die("could not execute query");
   $entires=$mysqli_num_rows($result2); #find number of entries
   foreach (array_column($result2, 'stationery_name') as $option) 
  #Echo an option for each entry
   {
    echo'
    <option value="'.$option.'">'.$option.'</option>';
   }
   echo'</select> and I would like <input type="text" name="amount"> of them <input type="submit" value="Submit">'; 
}
?>

Solution

  • You have some issues in your code.
    1. Incorrect implementation of array_column.
    First, mysqli_query returns an object (result object), not an array. You should fetch rows from the result object.
    2. Which one do you use?
    In your SQL you wrote SELECT 'name' FROM stationery, but you called it on array_column with 'stationery_name.'
    3. You have a typo on your script when you called $mysqli_num_rows($result2).it should be mysqli_num_rows($result2)

    Here's how you should do it, as follows:

    $sql2 = "SELECT name FROM stationery";
        $result2 = mysqli_query($dbc, $sql2) or die("could not execute query");
        
        while ($row = mysqli_fetch_assoc($result2)) {
            $option = htmlspecialchars($row['name']); 
            echo '<option value="'.$option.'">'.$option.'</option>';
        }
     
    

    Or if you insist on implementing array_column, here's how to do it properly:

    $sql2 = "SELECT name FROM stationery";
    $result2 = mysqli_query($dbc, $sql2) or die("could not execute query");
    
    // Try to fetch all rows into an associative array
    $rows = mysqli_fetch_all($result2, MYSQLI_ASSOC);
    
    // Now you can use array_column to get all "name" values as a simple array
    $names = array_column($rows, 'name');
    
    // variables $names is now an array of all the names
    foreach ($names as $option) {
        echo '<option value="' . htmlspecialchars($option) . '">' . htmlspecialchars($option) . '</option>';
    } 
    

    I hope this can help you.