June 17, 2012

PHP loop within a loop, option selected?

Question by David

Using PHP I echo out table rows in a loop like this:

<?php
/* SQL STUFF */

  while ($row = mysql_fetch_array($select_courseelements)) {
   echo "<tr>n";
    echo "<td>".$row['scpe_name']."</td>n";
    echo "<td>".$row['scpe_days']."</td>n";
   echo "</tr>n";
  }

Now I would like to include a <select> element with 5 predefined <option> values inside a <td> running with the loop. The option values will be 1 to 5.

There is also a column inside the $row loop that holds a value of 1 to 5 ($row['scpe_grades_status']).

Each time this value is equal to the one in the <select> I want it to change it to selected='selected'.

Would this be possible?

My <select> will look something like this when it’s beeing run in the loop:

echo "<td>n";
echo "<select id='elements_grade'>n";
        echo "<option value='1'>Registrerad</option>n";
        echo "<option value='2'>Ej påbörjad</option>n";
        echo "<option value='3'>Pågående</option>n";
        echo "<option value='4'>Godkänd</option>n";
        echo "<option value='5'>Deltagit</option>n";
        echo "<option value='6'>Ej deltagit</option>n";
echo "</select>n";
echo "</td>n";

Answer by piers

$array = array('Registrerad' => 1, 'Ej påbörjad' => 2, 'Pågående' => 3, 'Godkänd' => 4, 'Deltagit' => 5, 'Ej deltagit' => 6);

foreach ($array as $key=>$value) {
    if ($value == $row['scpe_grades_status'])
        echo '<option value="'.$value.'" selected>'.$key.'</option>';
    else
        echo '<option value="'.$value.'">'.$key.'</option>';
}

Something like that?

Answer by Starx

Sure, build the values from a loop. and you can compare the values from that part.

for($i = 1; $i<=5; $i++) {
   echo "<option value='$i'";
   echo ($row['scpe_grades_status'] == $i) ? " selected='selected'": "";
   echo ">...."</option>"
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!