Skip to content
Advertisement

Generating element with php script by the php script

I am trying to learn php and now I am stucked with one thing. I have the code like this:

<select name = "Option1" id ="Option1">
 <option value="0">Option1</option>
  <?php
   include ("db_connect.php");
   $option1 = $pdo->query("SELECT * FROM options");
   while($row = $option1->fetch(PDO::FETCH_ASSOC)){
    echo '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
   }
  ?>
</select>

Which is select element with options from database. But I need 5 of them and copying this piece of code 5 times just doesn’t make sense, or am I wrong?

I tried something like this:

     function renderSelect()
    {
        for ($a = 0; $a < 5; $a++){
            echo '<select>
                    <option value="0">Option ' . $a . '</option>
                    ' . renderOptions($a) . '
                  </select>';
        }
    }


    function renderOptions(){

   include ("db_connect.php");
   $option1 = $pdo->query("SELECT * FROM options");
   while($row = $option1->fetch(PDO::FETCH_ASSOC)){
    echo '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
   }
  }

And then just call the renderSelect, but it’s not working how expected.

Can you please give me little advice what to do here?

Thanks a lot I appreciate it!

Advertisement

Answer

Try to use return in your second function. If you echo it in the second function, it will add the echo output to the beginning, where you called the function. You create a String, where you add all your options to it and then return that string.

function renderOptions(){

   include ("db_connect.php");
   $option1 = $pdo->query("SELECT * FROM options");

   $string = "";
   while($row = $option1->fetch(PDO::FETCH_ASSOC)){
    $string .= '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
   }

   return $string;
}

And another point to mention, you are calling renderOption function and passing $a to a function, which takes to parameter.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement