Trying to make a dynamic dropdown in php from database - php

I got a little question I want to make a loop so I have a dropdown menu with the data. For example: A user has a beginning time of 12:00:00 and an end time of 14:00:00. The loop is supposed to pick out 30 min, so that you have a dropdown menu with 12:00:00, 12:30:00, 13:00:00, 13:30:00 and 14:00:00.
I will get the following data
$starttime = 12:00:00
$endtime = 14:00:00
$talktime = 00:30:00
now I want to make a dropdown menu from it that it loops.
here is my example how I thought it would work.
for ($endtime = $starttime + $talktime){}
But as the code works I want to check the database if the data already exist. I know how to do that part only the loop I don't know.
Already thank you for the help.

<?php
$starttime = new DateTime( '12:00:00' );
$endtime = new DateTime( '14:00:00' );
?>
<select>
<option></option>
<?php
for( $i = $starttime; $i <= $endtime; $i->modify( '+ 30 minutes' ) )
{
?>
<option> <?php echo $i->format( 'H:i' ); ?> </option>
<?php
}
?>
</select>
Each loop adds 30 minutes to the time.

You can try this
<?php
$starttime = new DateTime("12:00:00");
$endtime = new DateTime("14:00:00");
?>
<select name="" id="input" class="form-control" required="required">
<?php
while($starttime <= $endtime)
{
echo "<option value='".$starttime->format('H:i:s')."'>".$starttime->format('H:i:s')."</option>";
$starttime = date_add($starttime, date_interval_create_from_date_string('30 min'));
}
echo " </select>";

Try this
<?php
$starttime = "12:00:00";
$endtime = "14:30:00";
$starttime = strtotime($starttime);
$endtime = strtotime($endtime);
$tNow = $starttime;
while($tNow <= $endtime){
echo date("H:i:s",$tNow)."<br>";
$tNow = strtotime('+30 minutes',$tNow);
}
?>

Related

How to create Php Timepicker in 12 hrs format

I have used php timepicker in my project and it is 24 hrs format but in new requirement I need to implement this only 12 hrs format because I have to check time in AM PM format to compare with passed variable value. so what is the process to create in 12 hrs format
<?php
$time = strtotime('10:00');
$end_time = strtotime('20:00');
$end_time = date("h:i a",$end_time);
echo '<select>';
while($time <= $end_time){
$optionvalue = date("H:i",$time);
echo '<option value="'.$optionvalue
.'">'.$optionvalue.'</option>';
$time = strtotime('+15 minutes',$time);
}
echo '</select>';
?>
You need to use date('h:i a') to get meridiem am,pm
$end_time = strtotime('20:00');
$optionvalue = date("h:i a",$end_time);
echo $optionvalue;
Like Demo
/* start and end times converted to DateTime objects */
$start=new DateTime( date( DATE_ATOM, strtotime('10am') ) );
$end=new DateTime( date( DATE_ATOM, strtotime('8pm') ) );
$interval=new DateInterval('PT15M');
/* ensure the initial time is part of the output */
$start->sub( $interval );
$slots=array();
while( $start->add( $interval ) <= $end )$slots[]=$start->format('H:ia');
printf('<select name="times"><option>%s</select>', implode( '<option>', $slots ) );
document.querySelector('select[name="times"]').onchange=(e)=>{
alert( e.target.value )
}
<select name="times">
<option>10:00am
<option>10:15am
<option>10:30am
<option>10:45am
<option>11:00am
<option>11:15am
<option>11:30am
<option>11:45am
<option>12:00pm
<option>12:15pm
<option>12:30pm
<option>12:45pm
<option>13:00pm
<option>13:15pm
<option>13:30pm
<option>13:45pm
<option>14:00pm
<option>14:15pm
<option>14:30pm
<option>14:45pm
<option>15:00pm
<option>15:15pm
<option>15:30pm
<option>15:45pm
<option>16:00pm
<option>16:15pm
<option>16:30pm
<option>16:45pm
<option>17:00pm
<option>17:15pm
<option>17:30pm
<option>17:45pm
<option>18:00pm
<option>18:15pm
<option>18:30pm
<option>18:45pm
<option>19:00pm
<option>19:15pm
<option>19:30pm
<option>19:45pm
<option>20:00pm
</select>

How to loop through time in select box PHP

I have a select drop down where I want to list times in the format of HH:MM with 1 minute intervals. so the list will start at 00:00 and finish at 23:59
I understand how to create a loop in a select drop down that will output 0-10
<select><?php for($i=0; $i<10; $i++){echo "<option>" . $i . "</option>";} ?>
</select>
and I understand how to output the time as HH:MM
<option><?php echo date('h:i', $supportrequest->startTime); ?</option>
But I can't work out how to do a combination of the two as I'm not sure what the parameters of the for loop should be
Using DatePeriod it'd be like that:
<?php
$begin = (new DateTime())->setTime(0,0,0); // create start point
$end = (new DateTime())->setTime(23,59,59); // create end point
$interval = new DateInterval('PT1M'); // set the interval to 1 minute
$daterange = new DatePeriod($begin, $interval ,$end); // create the DatePeriod
echo "<select>";
foreach($daterange as $date){ // loop through that period
echo "<option value='".$date->format("H:i") . "'>".$date->format("H:i")."</option>\n";
}
echo "</select>";
Using these classes makes it now easy to modify if you f.e. only want to have every 30 minutes, or need a different output format.
Do you really want to have a drop-down with one thousand, four hundred and forty option values (24 * 60 = 1440)? I think it would be better to have two <select> elements. You could style them to sit next to each other with a : in the middle if you wanted to keep the 'H:m' look.
<select id="hours">
<?php
for ($h = 0; $h < 24; $h++) printf("<option value=\"$h\"" . (!$h ? " selected" : "") . ">%02d</option>", $h);
?>
</select>
<select id="minutes">
<?php
for ($m = 0; $m < 60; $m++) printf("<option value=\"$m\"" . (!$m ? " selected" : "") . ">%02d</option>", $m);
?>
</select>
Converted Mukyuu's comment into an answer:
<select>
<?php
for($h=0; $h<24; $h++){
for($i=0; $i<60; $i++){
$time = date('h:i',strtotime($h.':'.$i));
echo "<option>".$time."</option>";
}
}
?>
</select>

Calculate age in php

Hey guys I am working on my colleague project and he used below code to store age from database and shows age in view
He select date and month from select tag.
view BOD select tag image
<?php $today = date("Y");
$year = $today - 18;?>
<select class="form-control" id="date" name="day" >
<option label=01 value=01>01</option>
<option label=02 value=02>02</option>
<option>.......</option>
<option label=30 value=30>30</option>
<option label=31 value=31>31</option>
</select>
<select class="form-control" id="month" name="month" >
January
<option label=January value=01>January</option>
February
<option label=February value=02>February</option>
<option>.......</option>
November
<option label=November value=11>November</option>
December
<option label=December value=12>December</option>
</select>
<select class="form-control" id="year" name="year" >
<?php for($i = 0; $i <= 75; $i++):?>
<option value=<?=$year?>><?=$year?></option>
<?php echo $year = $year -1 ;?>
<?php endfor;?>
</select>
result image
controller
public function user_register()
{
$data = array(
'u_day'=>$this->input->post('day'),
'month'=>$this->input->post('month'),
'year'=>$this->input->post('year'),
'age'=>$this->getAge($this->input->post('year')),
);
$id = $this->admin_model->insertData('users',$data);
$sess = array(
'userid'=>$id,
'fname'=>$this->input->post('first_name'),
'mname'=>$this->input->post('middle_name'),
'lname'=>$this->input->post('last_name'),
'gender'=>$this->input->post('gender'),
'reg'=>'1',
);
$this->session->set_userdata($sess);
redirect($this->config->item('base_url').'profile/basic_details');
}
public function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
//print_r($age);exit;
return $age;
}
It works perfectly when I select any other date.
but when I select (01/01/2000) date it store age in database as -1
Generate the birth date by concatenating the strings.
$date1 = date_create("2013-03-15"); // generate this by "$date-$month-$year"; // your case
$date2 = date("Y-m-d"); // get today's date
$diff = date_diff($date1,$date2); //here you get the difference
You can apply mathematical operations to get exact exact years and months.
**Php Version >= 5.3**
# **get date and change date formate**
$from = new DateTime('1970-02-01');
$to = new DateTime('today');
echo $from->diff($to)->y;
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
**Mysql Version >= 5.0**
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
I can not see any code in the question that attempts to calculate the age of a user as suggested by the title of the question - consequently can not suggest how to edit the code appropriately. However, as I mentioned in my comment and has been used elsewhere in answers by #Danyal & #Anil, it would be easier and more reliable to use the DateTime class with it's associated methods.
The code below is just a quick rewrite of the question to make it viable and enable the demo to work. The code that processes the user selection is within the if code block below and should be well commented.
$today = date( 'Y' );
$year = $today - 18;
$maxyears = 120;
$html=array();
$html[]='<form method="post">';
/* days */
$html[]='<select class="form-control" name="day">';
for( $i=1; $i <= 31; $i++ )$html[]=sprintf('<option value=%d>%d',$i,$i);
$html[]='</select>';
/* months */
$html[]='<select class="form-control" name="month">';
for( $i=1; $i <= 12; $i++ )$html[]=sprintf('<option value=%d>%s', $i, date('F',mktime( 0, 0, 0, $i ) ) );
$html[]='</select>';
/* years */
$html[]='<select class="form-control" name="year">';
for( $i=$year; $i >= ( $today - $maxyears); $i-- )$html[]=sprintf('<option value=%d>%d',$i,$i);
$html[]='</select>';
$html[]='<input type="submit" />';
$html[]='</form>';
/* output menus */
echo implode( PHP_EOL, $html );
/***** Process Form submission and calculate Age *****/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['day'], $_POST['month'], $_POST['year'] ) ){
/* Establish rules for filtering POSTED data */
$args=array(
'day' => FILTER_SANITIZE_NUMBER_INT,
'month' => FILTER_SANITIZE_NUMBER_INT,
'year' => FILTER_SANITIZE_NUMBER_INT
);
/* Filter POST data */
$_POST=filter_input_array( INPUT_POST, $args );
/* Extract data to variables */
extract( $_POST );
/* create a new date using supplied POST data - using `mktime` to generate a valid timestamp */
$date = date( 'Y-m-d', mktime( 0, 0, 0, $month, $day, $year ) );
/* create DateTime objects and calculate age ( date difference ) */
$now = new DateTime();
$dob = new DateTime( $date );
/* use the `diff` method to find the difference between two dates */
$diff = $now->diff( $dob );
/*
show the age
use the `$diff->format('%y')` method or the shorthand method `$diff->y`
*/
printf('Age: %d', $diff->y ); #same as $diff->format('%y');
Looking at the getAge function produced very odd results - so I tweaked it and arrived at the following - seems to more or less do what is needed.
function getAge( $date ) {
$now = date( 'Y' );
$diff = $now - $date;
if( strtotime( '+' . $diff . ' years', strtotime( $date ) ) < time() ) $diff--;
return $diff;
}
echo getAge( 2017 ); // -> 1
echo getAge( 2000 ); // -> 18

Hide past time in simple PHP timepicker

My first block of code finds the nearest hour and stores it in a $nextHour variable.
I want to use this value in my second lot of code so it only shows future time in the dropdown. How do I update my second block of code to achieve this?
<?php
$date = new DateTime();
$nextHour = (intval($date->format('H'))+1) % 24;
echo $nextHour.':00'; // 5
?>
<?php
$start = "09:00";
$end = "20:00";
$tStart = strtotime($start);
$tEnd = strtotime($end);
$tNow = $tStart;
?>
<select name="callbacktime" id="callbacktime">
<?php
while($tNow <= $tEnd){
echo '<option value='.date("H:i",$tNow).'>'.date("H:i",$tNow).'</option>';
$tNow = strtotime('+1 hour',$tNow);
}
?>
</select>
$tStart = max([strtotime('09:00'), time()]);
I'd go with something like this as it saves having to do a check every loop as I previously mentioned in my comment.

Get the Year/Month/Day from a datetime in php?

I used date('w', timestamp) and date('w', timestamp) to know the day, date('n', timestamp) for months, etc.
Now I'm using datetime and I'd like to know what are the equivalent functions to get a day, a month, etc from a datetime.
PS: I know I could use UNIX_TIMESTAMP() in a SQL query but I prefer avoiding timestamps using in my code.
Use DateTime with DateTime::format()
$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
Try below code if you want to use php loop to display
<span>
<select name="birth_month">
<?php for( $m=1; $m<=12; ++$m ) {
$month_label = date('F', mktime(0, 0, 0, $m, 1));
?>
<option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
<?php } ?>
</select>
</span>
<span>
<select name="birth_day">
<?php
$start_date = 1;
$end_date = 31;
for( $j=$start_date; $j<=$end_date; $j++ ) {
echo '<option value='.$j.'>'.$j.'</option>';
}
?>
</select>
</span>
<span>
<select name="birth_year">
<?php
$year = date('Y');
$min = $year - 60;
$max = $year;
for( $i=$max; $i>=$min; $i-- ) {
echo '<option value='.$i.'>'.$i.'</option>';
}
?>
</select>
</span>

Categories