How can I create a dropdown of a form from a database table in php?

I am trying to code a function that creates a dropdown list of school names selected from a database. It does its best by creating the dropdown, but it doesn't put anything in the dropdown. Here is the code:

function schoolDD($name, $selected){
   $select = '';
   if( $selected != null )
   {
      $select = $selected;
   }

     $qry = "select *   
             from   school
             order by name, id
             where display = 'Y'";

     $schools = _execQry($qry);


   $html = '<select name="'.$name.'" >';

   foreach( $schools as $s ){
      $html .= '<option value="'. $s['id'] .'"';
      if( $select == $s['name'] ){
         $html .= 'selected="selected"';
      }
      $html .= '>'. $s['name'] . '</option>';

   }
   $html .= '</select>';
   return $html;
}

      

0


a source to share


3 answers


The problem has been resolved. This is because in the request I had the order up to that point. It should have been:

$qry = "select *   
             from   school
             where display = 'Y'
             order by name, id";

      



Not:

 $qry = "select *   
             from   school
             order by name, id
             where display = 'Y'";

      

0


a source


Looks good, but it's hard to tell without knowing what _execQry is doing.

If you add the line



print_r($schools);

      

after calling _execQry, are you definitely fetching the results from the database?

0


a source


I'm glad you found your answer, but I haaattee php and html mixed like this.

how about tsomethign like this ...

<?php

$schools = getSchools();
$selectedSchool = 'sfgsfgd';
$name = 'asdfsafd';

?>

<select name="<?= $name ?>">
<?php foreach( $schools as $s ): ?>
    <option value="<?= $s['id'] ?>"<?php if( $s['name'] == $selectedSchool ): ?> selected="selected"<?php endif; ?>><?= $s['name'] ?></option>
</select>

      

0


a source







All Articles