I have a form which submits an array of fields e.g:
<input class="form-control" type="date" name="schedule-date[]">
<input type="text" class="form-control" name="schedule-start[]">
<input type="text" class="form-control" name="schedule-end[]">
with php I am trying to get the day of the week from the date foreach so far I only get the last day. Here's my code.
$date = $_POST['schedule-date'];
foreach($date as $d){
$day = date("l", strtotime($d));
}
$start = $_POST['schedule-start'];
$end = $_POST['schedule-end'];
foreach( $date as $key => $n ) {
echo $date[$key]." ".$day." "$start." ".$end;
echo ;
}
I get:
2018-12-01 Sunday 9start 18end
2018-12-02 Sunday 10start 20end
In the above the sunday is being repeated. How can I get the correct days? e.g. Saturday and Sunday etc.
You are not calculating the day for each date. You are using the already calculated day.
$date = $_POST['schedule-date'];
// rest of the code
foreach( $date as $key => $n ) {
$day = date("l", strtotime($n)); // move this line inside for loop
echo $date[$key]." ".$day." "$start." ".$end;
}
Related
I want to print the date every three months before one year past,from the date selected by user, but when i made the increment the loop breaks and only prints the fist date, could help me, please
this is my code in PHP
$fecha = date('m/d/Y',strtotime($_POST['fecha']));
printf( date('d/m/Y',strtotime($fecha)).'----');
$fin = date('m/d/Y',strtotime($fecha."+ 1 year"));
printf(date('d/m/Y',strtotime($fin)).'----');
if($fecha<$fin){
$fecha = date('m/d/Y',strtotime($fecha."+ 1 month"));
printf( date('d/m/Y',strtotime($fecha)));
}
<form method="POST" action="./fechas.php">
<input type="date" name="fecha" id="fecha">
<input type="submit" value="enviar">
</form>
This is the output:
And i want to print this:
15/10/2020----
15/11/2020----
15/12/2020---
...
You're repeatedly reformatting and reparsing dates and intervals with the most unreliable functions when there's an entire DateTime library to make your life easier.
$input = new DateTime('2020-09-24', new DatetimeZone('UTC'));
$past = (clone $input)->sub(new DateInterval('P1Y'));
$period = new DateInterval('P3M');
$cur = clone $past;
do {
echo $cur->format('Y-m-d') . "\n";
$cur->add($period);
} while( $cur <= $input );
Output:
2019-09-24
2019-12-24
2020-03-24
2020-06-24
2020-09-24
I have a PHP script which records things based on the day. So it will have a weekly set of inputs you would enter.
I get the data correctly, but when i do $day ++; it will increment the day, going passed the end of the month without ticking the month.
example:
//12/29
//12/30
//12/31
//12/32
//12/33
Where it should look like
//12/29
//12/30
//12/31
//01/01
//01/02
My script is as follows:
$week = date ("Y-m-d", strtotime("last sunday"));
$day = $week;
$run = array(7); //this is actually defined in the data posted to the script, which is pretty much just getting the value of the array index for the query string.
foreach( $run as $key=>$value)
{
$num = $key + 1;
$items[] = "($num, $user, $value, 'run', '$day')";
echo "".$day;
$day ++;
}
Should I be manipulating the datetime differently for day incrementations?
You can use
$day = date("Y-m-d", strtotime($day . " +1 day"));
instead of
$day++;
See live demo in ideone
You refer to $day as a "datetime" but it is just a string - that is what date() returns. So when you do $day++ you are adding 1 to "2015-12-02". PHP will do everything it can to make "2015-12-02" into a number and then add 1 to it, which is not date math. Here is a simple example:
<?php
$name = "Fallenreaper1";
$name++;
echo $name
?>
This will output:
Fallenreaper2
This is how I would do it, using an appropriate data type (DateTime):
<?php
$day = new DateTime('last sunday');
$run = array(7);
foreach ($run as $key => $value) {
$num = $key + 1;
$dayStr = $day->format('Y-m-d');
$items[] = "($num, $user, $value, 'run', '$dayStr')";
echo $dayStr;
$day->modify('+1 day');
}
To increase time you should use strtotime("+1 day");
here is simple example of using it
<?php
$now_time = time();
for($i=1;$i<8;$i++) {
$now_time = strtotime("+1 day", $now_time);
echo date("Y-m-d", $now_time) . "<br>";
}
?>
I have got strange issue with dates of events and I have tried hard to get it fixed but unable to do it.
I am attaching a screenshot of how I want to display the dates on the page :
In the picture the first event Deine Energie in Aktion! is a combination of 5 events with each event having its start date and end date.
The first part of the event is 1 day event which starts on 4th April and ends on 4th April. Similarly the second part is on 7th April, 3rd part on 9th April and 4th part on 20th April
The last part starts on 5th May and ends on 10th May.
The dates are stored in database in this format :
I am showing the dates for last part of event.
Event Start Date : 2013-05-05 00:00:00
Event End Date : 2013-05-10 00:00:00
So I want to display dates in the format shown in the picture.
There are multiple cases:
First is if all the dates are coming within a single month then we display the month name at the end only once.
Second is if months are changed then the month name will be shown after the date when the month is changed.
I am getting events dates in a while loop, so how do I compare the current event date with the coming event date in a loop.
This is the code I have used so far to get the dates from the database..
$nid = $row->nid;
$get_product_id = "SELECT product_id from {uc_product_kits} where nid='$nid'";
$res = db_query($get_product_id);
while ($get_product_id_array_value = db_fetch_array($res)) {
$prductid = $get_product_id_array_value['product_id'];
$start_date = db_query("select event_start,event_end from {event} where nid=%d",$prductid);
$start_date_value = db_fetch_object($start_date);
$end_value = $start_date_value->event_start;
$event_end_date = $start_date_value->event_end;
$TotalStart = date("d M Y", strtotime($end_value));
$TotalEnd = date("d M Y", strtotime($event_end_date));
$onlyMonthStart = date("M", strtotime($end_value));
$onlyMonthEnd = date("M", strtotime($event_end_date));
//$groupMonth = db_query("select event_start,event_end, month from {event} where nid=%d group by ",$prductid);
if($TotalStart == $TotalEnd ){
$startDay = date("d", strtotime($end_value));
$startMonth = date("M", strtotime($end_value));
if(in_array($startMonth,$newMonth)) {
echo $onlstartdate;
}
else {
$onlstartdate = date("d", strtotime($end_value));
echo $onlstartdate;
$tempStorage[] = $startMonth
}
//$newMonth[] = $startMonth;
}
}
Easiest would be to first collect all data from your query into e.g. array.
Only then iterate over the array. Having all data together will allow you to compare two consecutive date ranges to decide level of details you need to print for each.
Commented example:
// collect data from SQL query into structure like this:
$events = array(
array("event_start" => "2013-4-4", "event_end" => "2013-4-4"),
array("event_start" => "2013-4-7", "event_end" => "2013-4-7"),
array("event_start" => "2013-4-9", "event_end" => "2013-4-9"),
array("event_start" => "2013-4-20", "event_end" => "2013-4-20"),
array("event_start" => "2013-5-5", "event_end" => "2013-5-10"),
array("event_start" => "2014-1-1", "event_end" => "2014-1-2"),
);
// the actual code for range list generation:
for ($i = 0; $i < count($events); $i++)
{
// parse start and end of this range
$this_event = $events[$i];
$this_start_date = strtotime($this_event["event_start"]);
$this_end_date = strtotime($this_event["event_end"]);
// extract months and years
$this_start_month = date("M", $this_start_date);
$this_end_month = date("M", $this_end_date);
$this_start_year = date("Y", $this_start_date);
$this_end_year = date("Y", $this_end_date);
$last = ($i == count($events) - 1);
// parse start and end of next range, if any
if (!$last)
{
$next_event = $events[$i + 1];
$next_start_date = strtotime($next_event["event_start"]);
$next_end_date = strtotime($next_event["event_end"]);
$next_start_month = date("M", $next_start_date);
$next_end_month = date("M", $next_end_date);
$next_start_year = date("Y", $next_start_date);
$next_end_year = date("Y", $next_end_date);
}
// ranges with different starting and ending months always go
// on their own line
if (($this_start_month != $this_end_month) ||
($this_start_year != $this_end_year))
{
echo date("j M", $this_start_date);
// print starting year only if it differs from ending year
if ($this_start_year != $this_end_year)
{
echo " ".date("Y", $this_start_date);
}
echo "-".date("j M Y", $this_end_year)." <br/>\n";
}
else
{
// this is range starting and ending in the same month
echo date("j", $this_start_date);
// different starting and ending day
if ($this_start_date != $this_end_date)
{
echo "-".date("j", $this_end_date);
}
$newline = false;
// print month for the last range;
// and for any range that starts(=ends) in different month
// than the next range ends
if ($last ||
($this_start_month != $next_end_month))
{
echo " ".date("M", $this_start_date);
$newline = true;
}
// print year for the last range;
// and for any range that starts(=ends) in different year
// than next range ends
if ($last ||
($this_start_year != $next_end_year) ||
($next_start_month != $next_end_month))
{
echo " ".date("Y", $this_start_date);
$newline = true;
}
if ($newline)
{
echo " <br/>\n";
}
else
{
// month (and year) will be printed for some future range
// on the same line
echo ", ";
}
}
}
This outputs:
4, 7, 9, 20 Apr <br/>
5-10 May 2013 <br/>
1-2 Jan 2014 <br/>
A possibility to check if you need to print the month for the current date item is actually to check in the next item. Let me try to explain with pseudocode:
<?php
$month = 0; // Initialize $month variable to unset
// Loop over all your events
foreach($dates as $date) {
// Convert $date to a timestamp
// If the 'month' of the current $timestamp is unequal to $month
// it means we switch months and we have to print the $month first
if(date('m', $timestamp) != $month) {
echo $month; // Of course format how you want it to be displayed
// Set $month to the new month
$month = date('m', $timestamp);
}
// Print the rest of the event, like day numbers here
}
?>
Well, since you need to compare value from one loop to another, you won't be able to use echo directly.
You need to use temp variables. So with the first loop for the start date, you store $tmp_day_1 and $tmp_month_1 then with the end date loop you can compare both months and check if they are diferents. Then you can use echo. I hope I make my point :)
This is my data:
Day From: To:
Sunday 12PM 8PM
Monday 12PM 9PM
Tuesday 12PM 6PM
Wednesday 12PM 6PM
Thursday 12PM 6PM
Friday 12PM 5PM
Saturday 12PM 5PM
How do I go about using a for loop to insert the above data (from $_POST) into my MySQL database with PHP'S PDO? My input fields are named SundayTimeFrom, SundayTimeTo, MondayTimeFrom, MondayTimeTo, etc.
Pseudocode that I threw together really fast:
$sql = 'Insert INTO tableName (day, from, to) Values (:day, :from, :to)';
for(i = Sunday; I < Saturday; i++) //what do I do here?
{
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":day", $i, PDO::PARAM_STR);
$stmt->bindParam(":from", $_POST[$i + 'TimeFrom'], PDO::PARAM_STR);
$stmt->bindParam(":to", $_POST[$i + 'TimeTo'], PDO::PARAM_STR);
}
you can loop 7 times and use date('l',time()+24hours in secs) to get your days in letters.
Look at date('l') here http://php.net/date
But the best would be to change your $_POST to get something like $_POST['days'][0][from] = '10PM'; and $_POST['days'][0][to] = '8PM';
You can do this by writing : <input type="text" name="days[][from]" value="10PM" /> if i remember correct
or simply <input type="text" name="days[Monday][from]" value="10PM" /> and <input type="text" name="days[Monday][to]" value="8PM" /> and doing a foreach($_POST['days'] as $value)
As you can see you have a lot of solutions :)
If instead of SundayTimeFrom and SundayTimeTo the fields would have the names schedule[sunday][from] and schedule[sunday][to] you could use a foreach loop like
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":day", $day);
$stmt->bindParam(":from", $from);
$stmt->bindParam(":to", $to);
foreach( $_POST['schedule'] as $day=>$span ) {
someDataValidationHere($day, $span);
$from = $span['from'];
$to = $span['to'];
$stmt->execute();
}
(untested)
Say your array is
$schedule = array (sunday => array (from=>"12PM", to=> "8PM"),
monday => array (from=>"1PM", to=> "9PM"),
tuesday => array (from=>"2PM", to=> "10PM"),
wednesday => array (from=>"3PM", to=> "11PM"),
);
use _REQUEST["schedule"] and save in some array say $schedule.
now use foreach to save the array in the database.
foreach ($schedule as $day=>$temp1) {
foreach ($temp1 as $key=>$time) {
if($key == "from")
$from = $time;
else if($key == "to")
$to = $time;
}
$sth = $this->db->prepare("Insert INTO tableName (day, from, to) Values (:day, :from, :to)");
$sth->execute(array(':day'=> $day, ':from'=> $from, ':to'=> $to));
}
How do you create a select with the option of 2 days ahead from today picked as the default option (i.e. a 48 hour window) in PHP? This is the code I'm using so far but it doesn't work unfortunately!
<?php
$weekday = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$days = range (1, 31);
$currentDay = date('F');
echo "<select name='weekday'>";
foreach ($days as $value) {
$default = ($value == $currentDay)?'selected="selected"':'';
echo '<option '.$default.' value="'.$value.'">'.$value."</option>\n";
}
echo '</select> ';
?>
I'm confused as to what your code does.
As far as I can tell $weekday is not used after being instantiated, and you are setting $currentDay to the text representation of the current month (e.g. September).
But if you want to get the day of month of the day 48 hours from now:
$two_days_ahead = date('j', strtotime('+ 48 hours'));