eniac05
eniac05

Reputation: 491

how to compare date from php and date from data base mysql?

i have mysql table like this

enter image description here

My awal_pendaftaran column and akhir_pendaftaran_column have date type.

I want to set my HTML selected field to default select nama_periode which current date (ex:2015-08-2) is lie between awal_pendaftaran and akhir_pendaftaran.

I have try code like this

$date_now = date("Y-m-d");
$perQ="SELECT * FROM periode  where awal_pendaftaran >= CURRENT_DATE ORDER BY awal_pendaftaran";
$perQ2 = mysql_query($perQ) or die(mysql_error());;
$selected="";
while($perF=mysql_fetch_array($perQ2))
{
        $awal_mendaftar=$perF['awal_pendaftaran'];
        $akhir_mendaftar=   $perF['akhir_pendaftaran'];
    if ((strtotime($awal_mendaftar)<= strtotime($date_now)) && (strtotime($akhir_mendaftar)>= strtotime($date_now)) ){
        $selected="selected";
    } else { $selected="";}
    echo "<option value=\"$perF[id_periode]\" selected=\"$selected\" >$perF[nama_periode]</option>\n";

}

but my HTML select field always show "PERIODE 4" as selected data (i want PERIODE 2), any help?

Upvotes: 0

Views: 50

Answers (1)

sics
sics

Reputation: 1318

In html the value for the selected attribute ist optional. Whenever the option has a selected attribute the html interpreter assigns this option as selected. Thus you have to change your code a bit:

if(
    (strtotime($awal_mendaftar)<= strtotime($date_now)) 
    && (strtotime($akhir_mendaftar)>= strtotime($date_now)) 
){
    $selected = '';
} 
else { 
    $selected = 'selected="selected"';
}

echo '<option value="'.$perF['id_periode'].'" '.$selected.'>'.$perF['nama_periode']."</option>\n";

Upvotes: 2

Related Questions