Converting PHP date range to MYSQL individual dates - php

I have an availability calendar in which I am currently adding in dates one by one, and using a mysql query to determine if there exists a row with a certain date and changing the class of the day to "booked" (Red).
I would like to enter in a range into my form, and process it through php (or mysql) into multiple, individual dates. My date format is M/D/YYYY, or MM/DD/YYYY, both are accepted. Unfortunately, when I built my calendar, I did not use the date format in sql for entries, but used varchar.
Is there a way to enter into my form for example 1/1/2014-1/3/2014 and have php convert that to 1/1/2014, 1/2/2014, 1/3/2014, and then have a mysql INSERT query to insert multiple values at once?
if (empty($_POST) === false && empty($errors) === true) {
$adcp_data = array(
'date' => $_POST['date'],
'customer' => $_POST['customer'],
'notes' => $_POST['notes'],
);
insert_adcp($adcp_data);
header('Location: adcp.php?success');
exit();
the insert_adcp function looks like this:
function insert_adcp ($adcp_data) {
array_walk($adcp_data, 'array_sanitize');
$fields = '`' . implode('`, `', array_keys($adcp_data)) . '`';
$data = '\'' . implode('\', \'', $adcp_data) . '\'';
mysql_query("INSERT INTO `adcp` ($fields) VALUES ($data)");
}
My workaround and last resort will be to add multiple text inputs and just add multiple dates manually so I only have to submit once. But a range is so much faster!
As a last note, if I could have those multiple entries keep the "customer" and "notes" values for each date in the range that would be amazing. I am prepared to lose those fields though to make this work. Thanks

Something like:
$day = new DateTime($_POST['range_start']);
$end = new DateTime($_POST['range_end']);
$all_dates = array();
while ($day <= $end){
$all_dates[] = $day;
$day->add(new DateInterval('P1D'));
}
That will give you an array of DateTime objects each of which represents a day in your range. You can get each object back into a string by calling DateTime::format() and passing 'm/d/Y' as the format string.
As for getting multiple entries into MySQL, the INSERT syntax allows INSERT INTO table (column) VALUES (row1), (row2), ... (rowN)
(this is clearly not not tested or the final code you would use -- just written into this web form from memory ... you'll have to write it out properly with input sanitation and range checking and whatnot.)

Check if the value from the input match your range format, capture the parts and generate the from and to dates.
if (preg_match('%\A(?<fromMonth>\d{1,2})/(?<fromDay>\d{1,2})/(?<fromYear>\d{4})-(?<toMonth>\d{1,2})/(?<toDay>\d{1,2})/(?<toYear>\d{4})\Z%', $str, $res)) {
$dates['from'] = mktime(0, 0, 0, $res['fromMonth'], $res['fromDay'], $res['fromYear']);
$dates['to'] = mktime(0, 0, 0, $res['toMonth'], $res['toDay'], $res['toYear']);
}
Generate the range between from and to dates.
for ($date = $dates['from']; $date <= $dates['to']; $date = strtotime('+1 day', $date) ){
$dates['range'][] = date('m-d-Y', $date);
}

I think, strtotime is more usable for your case. You can found definition at php.net site:
http://php.net/manual/en/function.strtotime.php

Related

Error saving datetime to database after clicking buy on DoExpressCheckout

My problem is the following:
When DoExpressCheckout() is executed i have to save some data to Database, including the current time + X time
The type of the field of the database is set to "datetime"
I'm using the strtotime function in this way
date_default_timezone_set('Europe/Rome');
$currentTime = date("Y-m-d");
$expected = date('Y-m-d',strtotime($currentTime.'+ 7 days'));
echo $expected;
$sql = "INSERT INTO acquisti (durata,prezzi,expectedtime) VALUES (".$str.",".$resArray['AMT'].",".$expected.")";
echo $sql;
mysql_query($sql) or die("Errore di inserimento");
Here i have two problems:
1) The query always returns me error when putting the $expected variable into the expectedtime field
2) If i put it manually (just to try if i was stupid) it writes me 0000-00-00 (i've enabled the ALLOW_INVALID_DATES)
Any suggestions?
Thanks a lot
Your field type is 'datetime', but you are only sending date using the INSERT query.
You need to use date('Y-m-d H:i:s') instead of date('Y-m-d'), or if you need only the date change the type of the field to date.
Put values in enclosure:
$sql = "
INSERT INTO acquisti (
durata, prezzi, expectedtime
) VALUES (
'$str', '{$resArray['AMT']}', '$expected'
)
";
But you should really need to start using prepared statements.
If you wish to pass datetime, then you should format accordinaly, like Y-m-d H:i:s.
PHP example:
$expected = date_create('now')->modify('+7 day')->format('Y-m-d H:i:s');
MySQL example:
$sql = "
INSERT INTO acquisti (
durata, prezzi, expectedtime
) VALUES (
'$str', '{$resArray['AMT']}', DATE_ADD(NOW(), INTERVAL 7 DAY)
)
";

inserting date into mysql

I have a textbox on one of my forms, the user enters a date in the form of dd/mm/yy
but when i try to insert it into one of my tables in my database, it enters it as
0000-00-00. how can I fix this? I want it to show on this format on my database dd/mm/yy
this is my following insert where $start is the data variable
$query = "INSERT INTO paycheck (payCheckId,jobId,payRate,jobLocation,hoursWorked,startPeriod,empId)
VALUES('','$job_id','$pay_rate','$job_location','$hours','$start','$userId')";
$result = mysqli_query($db, $query); //we make the query
You can chose either MySQL to do this, or you can have PHP do it for you.
For MySQL related solution, please check STR_TO_DATE() function and for PHP the function date() does it.
Usage in STR_TO_DATE() is:
STR_TO_DATE( '$startPeriod', '%d/%m/%Y' )
Hence, the query will be:
INSERT INTO paycheck (payCheckId, jobId, payRate,
jobLocation, hoursWorked, startPeriod, empId)
VALUES( '', '$job_id', '$pay_rate',
'$job_location', '$hours',
STR_TO_DATE( '$startPeriod', '%d/%m/%Y' ), '$userId')
You need to reformat your date so MySQL can read it. The format the database saves to is yyyy-mm-dd. If you would like to display the date in the format it originally came in, simply use the date() function like so: $date = date("d/m/y", strtotime($dateFromDB));
This might be a long winded way of doing it, and there are better ways out there however, you can create your own function to reformat it:
function reformatDate($incorrectFormat) {
list($d, $m, $y) = explode("/", $input);
$todaysYearBeginning = substr(0, 2, date("Y", time()));
if(strlen($d == 1) {
$d = "0" . $d;
}
if(strlen($m == 1) {
$m = "0" . $m;
}
if(strlen($y == 1) {
$y = "0" . $y;
}
return $todaysYearBeginning . $y . "-" . $m . "-" . $d;
}
echo reformatDate("dd/mm/yy");
Following on from Dream Eater's answer, you can use DateTime::CreateFromFormat like so:
$oldDate = DateTime::createFromFormat('d/m/y', $dateFromDB);
$newDate = $oldDate->format('Y-m-d');

How to correctly use the DateTime feature below

I have a timepicker where the textbox (durationChosen) formats the time like this '00 Hrs 00 Mins 00 Secs'.. Now the problem is that I want this time to be inserted into the database but obviously the format is incorrect. I want the textbox format to remain the same but how can I insert the time correctly in the database with the correct format?
At the moment the code below is causing the page not to load and because of this it is not inserting anything in the database. Have I coded the DateTime feature below incorrectly:
Below is the code for the INSERT VALUES:
$time = DateTime::createFromFormat( 'h * i * s *', $_POST['durationChosen'] );
$sql="
INSERT INTO Session (SessionDuration)
VALUES ('" . $time->format( 'H:i:s' ) . "')";
mysql_query($sql);
Maybe you could use this:
$time = date("H:i:s", strtotime($_POST["durationChosen"]));
Lets the datepicker return a valid ISO duration string like
$duration = "PT3H12M36S";
Now you can use DateInteval
$time = new DateTime;
$time->add(new DateInterval($duration);
As a side note: MySQL accepts an ISO formatted string for every of its DATE*-typed columns
VALUES (' . $time->format('c') . ')
http://php.net/datetime

retrieve date from Mysql and spilt it to the specific list

i am trying to retrieve date from Mysql db to my html form in order to edit the records, now the way i used to insert the date into the database was getting Year - Month - Day each from a list and then unite them in one variable like this :
$dob = $_POST['Year'] . '-' . $_POST['Month'] . '-' .$_POST['Day'];
this will insert the value of $dob like this format 0000-00-00 in my table
the problem is that how i will retrieve this variable and split it each element to its specific list
what i tried seems useless and wrong which is this code
$row['userDateOfBirth'] = $year . '-' . $month . '-' . $day ;
then put each variable to (example:year)
<option value="1920" selected="selected"><? echo $year ; ?></option>
this did not work , how can i do this ?
Assuming you've got an actual date/datetime field, you can do the splitting inside MySQL:
SELECT YEAR(datefield), MONTH(datefield), DAY(datefield), etc...
which gives you three separate fields containing the individual date components. You could also do things like explode('-', $datestr) in PHP to decompose 'yyyy-mm-dd' into individual yyyy, mm, and dd chunks.
Lots of options, it's up to you to pick which one is easiest/best for your particular problem.
You can handle that on the client (php) side.
$year = date('Y', strtotime( $row['userDateOfBirth'] ) );
if you have an invalid date, $year will have 1970.
You could use
$row['userDateOfBirth'] = date("Y-m-d", strtotime($mysqlResultRow['dateField']));
Where basically you're telling the date() function to return a formatted string of the time passed to it, in this case created via strtotime().
Date() reference. The above example returns the date in "2000-01-01", see the reference for selecting the appropriate format for your project.

Comparing user inputted date with MySQL datetime field

I am trying to compare a user inputed date and time with a date and time stored in a MySQL database (datetime field being used). Even when the values appear to be exactly the same PHP still thinks they are different. Could anyone shed any light on what I am doing wrong?
The following gives me the date in the correct format: "2011-04-22 18:36:00" which is being generated from a date picker and 2 seperate text boxes for the hour and minute.
if(isset($_POST['enableReminder'])) {
$_POST['reminder_date'] = str_replace("/","",$_POST['reminder_date']);
$day3 = substr($_POST['reminder_date'],0,2);
$month3 = substr($_POST['reminder_date'],2,2);
$year3 = substr($_POST['reminder_date'],-4);
$taskReminderDate = $year3.'-'.$month3.'-'.$day3;
$taskReminderHour = $_POST['reminder_hour'];
$taskReminderMinute = $_POST['reminder_minute'];
$taskReminderDBpre = $taskReminderDate.' '.$taskReminderHour.':'.$taskReminderMinute.':00';
$taskReminderDB = date( 'Y-m-d H:i:s', strtotime($taskReminderDBpre) );
$taskReminderDB2 = "'".$taskReminderDB."'";
} else {
$taskReminderDB = 'NULL';
}
I then try to compare what's in the database, and if the values are different set a variable accordingly:
$taskReminderCompare = strtotime($row['reminder_date']);
if($taskReminderDB !== $taskReminderCompare) {
$taskReminderSent = 0;
} else {
$taskReminderSent = 1;
}
But it ALWAYS returns 0 even if I echo $taskReminderDB and $taskReminderCompare and they are exactly the same.
It seems your $taskReminderDB variable is created like this :
$taskReminderDB = date( 'Y-m-d H:i:s', strtotime($taskReminderDBpre) );
Which means it'll contain a string -- a date formated as YYYY-MM-DD hh:mm:ss
On the other hand, your $taskReminderCompare variable is created this way :
$taskReminderCompare = strtotime($row['reminder_date']);
Which means it'll contain a UNIX Timestamp -- which is an integer.
So, your $taskReminderDB and $taskReminderCompare variables don't seem to contain the same thing.
To be sure, you could use the var_dump() function to get some informations (value and type) about what's in those :
var_dump($taskReminderDB, $taskReminderCompare);
As a sidenote : even if those two variables contain the same value, as you are using the !== operator (and not the != one), you must be sure that the values are of the same type.
i.e. the 123456 integer is not equal to the '123456' string, if comparing them with !==

Categories