2

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 being 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";

3 Answers 3

7

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>"
}
Sign up to request clarification or add additional context in comments.

Comments

5
$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?

2 Comments

Thank's for the answer. There seems to be something wrong with your code though. It only generates one <option> with all array values on one single line
what if i want the selected data ? from db
0

Add a

<br>

after each

</option>

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.