I want to insert dynamic months into database like if user select March then I need to insert record for 12 months from March to Feburary. I am getting dynamic months but when I am trying to insert it into database it insert only first 12 months. I need to repeat the loop again from March to February if user click on add more button. This is my code :
$months = array();
$date="august";
$year= '2014';
//$y= (int)$year;
$currentMonth= date('m', strtotime($date));
$currentyear= date('Y', strtotime('+1 year'));
for($x = $currentMonth; $x < $currentMonth+12; $x++)
{
$months[] = date('F Y', mktime(0, 0, $currentyear, $x,1));
}
//print_r($months);
for($i=0; $i<=23 ; $i++)
{
echo $insert= "insert into month(month_name) values('".$months[$i]."')";
}
as your months array only has 12 values, you can't go to value 23 in that array. What you can do is run through the array twice from 0 to 11, like this:
for($j=0; $j<2 ; $j++)
{
for($i=0; $i<12 ; $i++)
{
echo $insert= "insert into month(month_name) values('".$months[$i]."')";
}
}
or as clyde indicated you can use a modulo operator, which doesn't make you waste 2 loops and thus is faster:
for($i=0; $i<24 ; $i++)
{
echo $insert= "insert into month(month_name) values('".$months[$i % 12]."')";
}
Maybe you can use the DateTime object to do this.
$string = '01-08-2013'; //input string from user
$StartDate = new DateTime($string);
$StopDate = new DateTime($string);
$StopDate->modify('+1 year');
while($StartDate < $StopDate) { //loop as long as $StartDate is smaller than $StopDate
echo "inserting " . $StartDate->format('d/m/Y') . ' into database ' . "<br/>";
//execute mysql query;
$StartDate->modify('+1 month');
}
Your question should state why you want this series of months in the database, as nobody normally does so. Normally people put timestamps on transactions/event records into a database and then report on them.
Related
RESOLVED in answer below
Creating a scheduling tool for my users and I am having an issue trying to increment my variable obtained from a dropdown selection:
$date_select = $_POST['date_select'];
I'm sure it's a textbook fix, but to put it simply...I need to increment $date_select by +1 week for 52 weeks.
I have a dropdown menu starting with the current date, and looping to the end of 365 days, incrementing by 1. No problem here.
<select name="date_select" form="create_schedule">
<?php
for($i = 0; $i <= 365; $i++){
$d=strtotime($i . " Day");
$day = date("n-j-y l", $d) . "<br>";
echo "<option>" . $day . "</option>";
}
?>
</select>
This selection is represented by:
$date_select = $_POST['date_select'];
Next to that, before submitting, users can select a radio button - either M, T, W, Th, F, Sat, or Sun to indicate if they would like to apply their request to that selected day, for every week, for the rest of the year. (Which is what I'm trying to do...which is: increment $date_select by "+1 Week" until the for loop is finished)
This selection is represented by:
$repeat = $_POST['repeat'];
This is the closest I've gotten...the code below increments for every "Monday" like I want for example...if $repeat == 'M', but the numerical dates are wrong...
if(isset($_POST['repeat'])){
for($i = 0; $i <= 52; $i++){
$date = strtotime($i . " week", strtotime($date_select));
echo date("n-j-y l", $date) . "<br/>";
}
For example: if the date selected is 7-4-16 Monday, the output is this:
11-26-07 Monday
12-3-07 Monday
12-10-07 Monday
12-17-07 Monday
12-24-07 Monday
12-31-07 Monday
1-7-08 Monday
And so forth...
Thank you in advance.
RESOLVED The issue was in the date format..."m-d-Y" is not equivalent to "m/d/Y" when incrementing days weeks or months in regards to how it is output. Somewhere along the lines, "American" date format values and "European" date format values were getting mixed up. I changed the date format within both of the for-loops and got it working.
"Note: Be aware of dates in the m/d/y or d-m-y formats; if the separator is a slash (/), then the American m/d/y is assumed. If the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential errors, you should YYYY-MM-DD dates or date_create_from_format() when possible."
http://www.w3schools.com/php/func_date_strtotime.asp
Here is the working solution in case anyone is trying to do something similar
<select name="date_select" form="create_schedule">
<?php
for($i = 0; $i <= 365; $i++){
$d=strtotime($i . " Day");
$day = date("m/d/Y l", $d) . "<br>";
echo "<option>" . $day . "</option>";
}
?>
</select>
if(isset($_POST['repeat'])){
$repeat = $_POST['repeat'];
echo "<br/>";
for($i = 0; $i <= 13; $i++){
$d=strtotime($i . " week", strtotime($date_select));
echo date("m/d/Y l", $d) . "<br/>";
}
}
So on PHP you have to classes that can be really helpfull doing that
\DateTime and \DateInterval
So to do what you want I would recommend
$firstDate = \DateTime::createFromFormat('Y-m-d', $date_select));
$baseDate = clone $firstDate;
$intervalToAdd = new \DateInterval('P1w')
if(isset($_POST['repeat'])){
for($i = 0; $i <= 52; $i++){
$date [$i] = $baseDate->add($intervalToAdd);
echo '<option>'.$date[$i]->format('Y-m-d').'</option>';
}
I want to loop a date so that every time date is increment by previous date. my code is here. plz reply anyone, thanks in advance
$today = date('Y-m-d');
for($i=1; $i<=4; $i++){
$repeat = strtotime("+2 day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
I want result as if today is 2016-04-04 than, 2016-04-06, 2016-04-08, 2016-04-10, 2016-04-12.
actually i want to make a reminder date where user enter reminder. lets a user want to add reminder today and want repeat it 5 time after 2days, 3days or what ever he wants, in next comming day. than how i repeat date with for loop.
Try this:
<?php
$today = date('Y-m-d');
for($i=1; $i<=4; $i++)
{
$repeat = strtotime("+2 day",strtotime($today));
$today = date('Y-m-d',$repeat);
echo $today;
}
Output:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
The easiest way is what answer
aslawin
The below example is to go through the date
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$step = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $step, $end);
foreach ($period as $dt)
{
<sample code here>
}
You can try this:
$today = date('Y-m-d');
for($i=1; $i<=8; $i++){
if($i%2 == 0){
$repeat = strtotime("+$i day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
In this example, you can use $i%2 == 0 with limit <= 8
Use a for loop with base 2, then directly output your dates:
for( $i=2; $i<9; $i=$i+2 )
{
echo date('Y-m-d', strtotime( "+ $i days" )) . PHP_EOL;
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
actually i want to make a reminder date where user enter reminder.
lets a user want to add reminder today and want repeat it 5 time after
2days, 3days or what ever he wants, in next comming day. than how i
repeat date with for loop.
I'll help with the above. First of all I will just say I have a huge personal preference towards the DateTime object over simply using date it's more flexible and a hell of a lot more readable in my opinion, so when working with dates I would always suggest using that over date()
So here is some Code:
$date = new DateTime(); // Pretend this is what the User entered. We got it via $_POST or something.
$interval = 2; // Repeat x times at y day intervals. (Not including the initial)
$repeatAmount = 2; // Repeat the reminder x times
for ($i = 0; $i <= $repeatAmount; ++$i) {
echo $date->format('d/m/Y');
$date->modify('+'. $interval .' day');
}
$date = new DateTime()Imagine this is the date the user entered, this is our starting point, our first reminder will at this time.
$interval and $repeatAmount are the interval in days, i.e. I want this to every 2 days and the amount of times you want it to repeat, in our example 2.
for ($i = 0; $i <= $repeatAmount; ++$i) { We want to loop as many times as the user says they want to repeat. Little note ++$i tends to be a very minor performance boost over $i++ in some scenarios, so it is usually better to default to that unless you specifically need to use $i++
echo $date->format('d/m/Y'); Simply print out the date, i'll let you handle the reminder logic.
$date->modify('+' . $interval . ' day'); Increment the dateTime object by the interval that the user has asked for, in our case increment by 2 days.
Any questions let me know.
I have written a round robin tournament generator in PHP for an online electronic sports league, and I need to calculate the dates for each game in the tournament. Games are played every Thursday and Sunday over the course of many weeks (the number of weeks is dependent on how many teams are participating). Given the starting week and the number of weeks what would be the best way to calculate those dates?
I'm guessing it requires using some combination of DateTime, DateInterval, and DatePeriod; but I am having trouble figuring out how it would be done.
Update:
Apologies for not providing the code before. Here is the solution I had originally come up with. I didn't know if there was a simpler way of doing it. The function was called submitSchedule where the dates were generated.
<html>
<body>
<?php
function roundRobin($teams) {
$len = count($teams);
$schedule = array();
for ($i = 0; $i < $len - 1; $i++)
{
$home = array_slice($teams, 0, $len / 2);
$away = array_slice($teams, $len / 2);
$day = array();
for ($j = 0; $j < $len / 2; $j++)
{
array_push($day, array($home[$j], $away[$j]));
}
array_push($schedule, $day);
$temp = $away[0];
for ($j = 0; $j < count($away) - 1; $j++)
{
$away[$j] = $away[$j + 1];
}
$away[count($away) - 1] = $home[count($home) - 1];
for ($j = count($home) - 1; $j > 1; $j--)
{
$home[$j] = $home[$j - 1];
}
$home[1] = $temp;
$teams = array_merge($home, $away);
}
return $schedule;
}
function roundRobinBalanced($teams)
{
$schedule = roundRobin($teams);
for ($i = 1; $i < count($schedule); $i+=2)
{
$schedule[$i][0] = array_reverse($schedule[$i][0]);
}
return $schedule;
}
function doubleRoundRobinBalanced($teams)
{
$sched2 = roundRobinBalanced($teams);
for ($i = 0; $i < count($sched2); $i++)
{
$sched2[$i] = array_reverse($sched2[$i]);
}
return array_merge(roundRobinBalanced($teams), $sched2);
}
function tripleRoundRobinBalanced($teams)
{
return array_merge(doubleRoundRobinBalanced($teams), roundRobinBalanced($teams));
}
function submitSchedule($schedule, $start, $intervals, &$con)
{
mysqli_query($con, "TRUNCATE TABLE matches");
$curDate = $start;
echo "<pre>";
for ($i = 0; $i < count($schedule); $i++)
{
for ($j = 0; $j < count($schedule[$i]); $j++)
{
$temp0 = $schedule[$i][$j][0];
$temp1 = $schedule[$i][$j][1];
$temp2 = date_format($curDate, "Y-m-d");
mysqli_query($con,"INSERT INTO matches (T1ID, T2ID, gameDate) VALUES ('$temp0', '$temp1', '$temp2')");
echo "<span style=\"background:lightblue;\">( " . date_format(new DateTime(), "Y-m-d H:i:s") . " )</span>" . "> INSERT INTO matches (T1ID, T2ID, gameDate) VALUES (". $schedule[$i][$j][0] . ", " . $schedule[$i][$j][1] . ", \"" . date_format($curDate, "Y-m-d") . "\")<br>";
}
date_add($curDate, date_interval_create_from_date_string($intervals[$i % count($intervals)]));
}
echo "</pre>";
}
$teams = array();
$con=mysqli_connect("localhost:3306","root","REMOVED","schedule");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Select all items from the 'teams' table and order them first in descending order by points, then in ascending order by 'teamName'
$result = mysqli_query($con,"SELECT * FROM teams");
while($row = mysqli_fetch_array($result))
{
array_push($teams, $row['TID']);
}
if (count($teams) % 2 == 1)
{
array_push($teams, null);
}
shuffle($teams);
$schedule = tripleRoundRobinBalanced($teams);
// echo "<pre>" . json_encode($schedule, JSON_PRETTY_PRINT, JSON_FORCE_OBJECT) . "</pre>";
echo "<pre>";
print_r($schedule);
echo "</pre>";
// ---- List of possible DateTime expressions ----
// thursday
// next thursday
// YYYY-MM-DD
// DD/MM/yy
// thursday + 1 day
$start = new DateTime("thursday"); // Indicates the date of the first game
$jump = array("3 days", "4 days"); // Indicates the time intervals of each game (e.g. If day 1 starts on thursday, day 2 starts on sunday, day 3 starts on thursday, etc.)
submitSchedule($schedule, $start, $jump, $con);
mysqli_close($con);
?>
</body>
</html>
The way to achieve this is by using PHP's DateTime classes as you guessed. They are really very useful. I would suggest a little function something like this:-
/**
* #param $startWeek ISO week number of the first week
* #param $numWeeks The number of weeks to run including the first
*
* #return \DateTime[] An array of DateTime objects
*/
function getPlayDays($startWeek, $numWeeks)
{
$numWeeks --;
$result = [];
$currYear = (int)(new \DateTime())->format('Y');
$oneDay = new \DateInterval('P1D');
// Start on the first Thursday of the given week.
$startDate = (new \DateTime())->setISODate($currYear, $startWeek, 4);
$endDate = clone $startDate;
$endDate->add(new \DateInterval("P{$numWeeks}W"));
// End on the Sunday of the last week.
$endDate->setISODate((int)$endDate->format('o'), (int)$endDate->format('W'), 7);
$period = new \DatePeriod($startDate, $oneDay, $endDate->add($oneDay));
foreach($period as $day){
if(4 === (int)$day->format('N') || 7 === (int)$day->format('N') ){
$result[] = $day;
}
}
return $result;
}
foreach(getPlayDays(1, 3) as $playDay){
var_dump($playDay->format('D m-d-Y'));
}
You didn't specify how you would identify the starting week, so I have assumed an ISO week number.
Output:-
string 'Thu 01-02-2014' (length=14)
string 'Sun 01-05-2014' (length=14)
string 'Thu 01-09-2014' (length=14)
string 'Sun 01-12-2014' (length=14)
string 'Thu 01-16-2014' (length=14)
string 'Sun 01-19-2014' (length=14)
See it working.
DateTime manual.
This function will quite happily cope with DST changes, leap years and weeks close to the start and end of the year thanks to the built in magic of the DateTime classes :)
proof or STFU.
Have a look at the strtotime function:
http://www.php.net/manual/en/function.strtotime.php
You could do something like this:
$startDate = "May 15, 2014";
$startDate = strtotime($startDate);
And you could get the start of the Sunday match by simply adding three days:
$nextDate = strtotime("+3 day", $startDate);
Your question is a bit vague, but I think this is what you were asking.
Let's say you have the timestamps of the day of starting week (06:00 AM time)...
Every other date will be 7 days (86400 seconds * 7) in the future.
Let's assume you will run this for 52 weeks (1 year)
$firstThu = 1234567890;
$firstSun = 9876543210;
$nextThus = array();
$nextSuns = array();
for($i=0; $i<52; $i++) {
$nextThus[] = date('d/m/Y', $firstThu + (86400 * 7 * $i));
$nextSuns[] = date('d/m/Y', $firstSun + (86400 * 7 * $i));
}
At the end of the loop you will have two arrays with all the 52 weeks dates.
Hi firstly heres my code.
<?php
function getDatesBetween2Dates($startTime, $endTime) {
$day = 86400;
$format = 'd-m-Y';
$startTime = strtotime($startTime);
$endTime = strtotime($endTime);
$numDays = round(($endTime - $startTime) / $day) + 1;
$days = array();
for ($i = 0; $i < $numDays; $i++) {
$days[] = date($format, ($startTime + ($i * $day)));
}
return $days;
}
///
$days = getDatesBetween2Dates(date('d-m-Y', strtotime('-3 weeks Monday')),date('d-m-Y', strtotime('+2 weeks Sunday')));
foreach($days as $key => $value){
$dayNumber = date('d', strtotime($value));
//echo $value;
echo "<div id=\"day\">
<div id=\"number\">$dayNumber</div>";
////////////sql seearch//\\\/////////
//Connect to db
include("../djwbt.php");
$sql = "SELECT * FROM daysummary WHERE date='$value'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$place = $row['place'];
$invoicedate = $row['date'];
}
/////////////end sql search//////////
echo "<div id=\"event\">$place</div>
</div><!-- end day -->";
}
?>
What i am trying to do is show all dates between two points and for each of the dates search my db using the date as a where clause. i have tried putting the search in a few places but im not getting the right results.
this gives me the same result in each date.
e.g. 17th = (empty) as in my db, 18TH = HOME (as in my db), 19th = HOME (not as in my db), 20th = HOME (this continues all the way through fore each)
the link in each fore each works perfectly?
Any help would be amazing.
I would make one statement that gets all the needed data from your database:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
then use the foreach loop for the results
Note that mysql_ functions are deprecated, Try switching to mysqli_ or PDO
I need help Select every other Wednesday starting on 5/2/12. This code below selects every other Wednesday starting on the week it currently is. But i need to set the beginning week. I am familiar with PHP, but not familiar with php dates. So please be as specific as possible.
I found this:
$number_of_dates = 10;
for ($i = 0; $i < $number_of_dates; $i++) {
echo date('m-d-Y', strtotime('Wednesday +' . ($i * 2) . ' weeks')). "<br>".PHP_EOL;
}
Use mktime to create your starting date and pass that as the second argument to strtotime so that counting starts from there:
$startDate = mktime(0, 0, 0, 5, 2, 2012); // May 2, 2012
for ($i = 0; $i < $number_of_dates; $i++) {
$date = strtotime('Wednesday +' . ($i * 2) . ' weeks', $startDate);
echo date('m-d-Y', $date). "<br>".PHP_EOL;
}
See it in action.
Give it a date in the string, instead of "Wednesday" (that chooses the next Wednesday), write:
strtotime('20120502 +' . ($i * 2) . ' weeks'))
To choose that date. (Format is yyyymmdd).
If you have PHP 5.2.0 or newer, you can do it easily this way:
$date = new DateTime('2006-05-02');
for ($i=0; $i<10; $i++) {
echo $date->format('m-d-Y').'<br/>'.PHP_EOL;
$date->modify('+1 week');
}
You could also use the DatePeriod and DateInterval classes to make life easier.
Standard disclaimer: both of the classes above require PHP >= 5.3.0.
$number_of_dates = 10;
$start_date = new DateTime("5/2/12");
$interval = DateInterval::createFromDateString("second wednesday");
$period = new DatePeriod($start_date, $interval, $number_of_dates - 1);
foreach ($period as $date) {
echo $date->format("m-d-Y") . "<br>" . PHP_EOL;
}