0

function.php

 function getCategories($id = null) {
      $categoried = array();

       $query = mysql_query("SELECT id,name FROM `categories`");

      while ($row = mysql_fetch_assoc($query) ) {
              $categories [] = $row;
     }

dropdown.php

...
             <select name="category">
                  <?php 
                     foreach(getCategories() as $category){
                  ?>
                  <option value=" <?php echo $category['id'];?> " > <?php echo $category['name'];?> </option>
                  <?php
    }
    ?>

I am trying to use a drop down menu, but it seems like I can't figure out on how to populate the drop-down menu with items from mySql database. The code above doesn't fill my drop down menu. So can someone tell me where I have made the mistake

Ron
  • 41
  • 3
  • 8
  • don't use mysql_* is bester to use mysqli_* ...check this link https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – Ahmed Ziani Mar 29 '15 at 00:34

1 Answers1

1

Return the $categories array from your function:

function getCategories() {
    $categories = array();
    $query = mysql_query("SELECT id,name FROM `categories`");
    while ($row = mysql_fetch_assoc($query) ) {
        $categories[] = $row;
    }

    return $categories; // return the results array
}

Returning an array in a function makes the execution of the function interchangeable with arrays in expressions, such as foreach ( $array as $value ) {. In place of $array you can put a function that returns an array: foreach ( returnsArray() as $value ) {. In this case: foreach ( getCategories() as $category) {.

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37