user2148116 user2148116 - 3 months ago 17
MySQL Question

Set default value extracted from mysql database for dropdown list php

I have a php page that asks the user to enter his birth date from 3 dropdown lists(one for year, one for month, one for day), then, I store these values in mysql database in one date variable as follow:

$date= $BirthYear.'-'.$BirthMonth.'-'.$BirthDay;


now, I have another php form that let the user edit his information but the problem is: how to set the default values for the three drop down lists in the edit form to the stored date values?
I fetch the date values from database as following:

$DOB_Y= $row['YEAR(BirthDate)'];
$DOB_M= $row['MONTH(BirthDate)'];
$DOB_D= $row['DAY(BirthDate)'];


My dropdown list code for birth DAY is:

<select id="form_dob_day" name="dob_day" class = "option" required >
<?php
for($i=01; $i<=31; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>


and the same for MONTH and YEAR.

I used this code but it doesn't work:

<select id="form_dob_day" name="dob_day" class = "option" required >
<?php
for($i=01; $i<=31; $i++)
{


echo "<option value=".$i. if ($DOB_D==$i) echo "selected" ">".$i."</option>";
}
?>
</select>


thanks in advance,

Answer

You have an error in your syntax, this should correct it:

<select id="form_dob_day" name="dob_day"  class = "option" required >
<?php 
    for($i = 1; $i <= 31; $i++)
    {
        echo '<option value="' . $i . '" ' . (($DOB_D == $i) ? "selected"  : '') . '>' . $i . '</option>';
    }
?>
</select>