Fadly Dzil
Fadly Dzil

Reputation: 2206

Dropdown list for time : hour and minutes separately on html and php

I created two dropdown list for manage time. First dropdown list to manage hour in 24 hours format (Office Time) is 08.00-21.00. The second dropdown list is minutes 00-59. I blank.

 <select id="Hour" class="input-small">
    <?php
       for ($i=8; $i<=21; $i++){
         echo "<option value='".$i."'>" . $i ."</option>";
       }
    ?>
 </select>

 :

 <select id="Minutes" class="input-small">
    <?php

        for ($i=0; $i<=59; $i++){
             echo "<option value='".$i."'>" . $i ."</option>";
      }
    ?>
 </select>

How to created this in php code ?

Sorry, the problem is in hour format : let see. if 01, it printed 1. So, if user wanna to insert 01.00, it failed because the result is: 1.0 . It gives me error when I insert to database.

Upvotes: 0

Views: 7774

Answers (2)

Raptor
Raptor

Reputation: 54212

Your suggested format (08.00-21.00) is incompatible with database (well, I assume you're using MySQL). You didn't mention what is the data type of the column, but as in your case, you should be storing the information as VARCHAR.

To format the post values to your suggested format, you can use the following:

$open_time = str_pad($_POST['hour'], 2, '0', STR_PAD_LEFT) . '.' . str_pad($_POST['minute'], 2, '0', STR_PAD_LEFT);

p.s. you should give a name to your input <select>

Upvotes: 1

Thomas Mair&#233;
Thomas Mair&#233;

Reputation: 554

If you want to keep format : 01,02, ... you can make a function in php after submitting form to add 0 before the value under 10. Like :

if($_POST['Hour'] < 10 ){
    $concat = "0".$_POST['hour'];
}

But it's not very clean. You can use str_pad() : http://php.net/manual/fr/function.str-pad.php

(Thanks Raptor for the comment)

Upvotes: 1

Related Questions