Best method to input and validate custom datetime in PHP form - php

This is a double question in terms of front end usability and PHP DATE_TIME validation.
I am working on a site for a client who would like to add the date he finished a project (so the projects can be listed in that order). He will be the only one using the admin interface, so I would like it to be as simple as possible.
I am storing the dates as DATE_TIME in a SQLite db.
I would like to require the client enter at least the year and month, with the option to add day, hour, minute, second to the DATE_TIME. If these are not set they will default to the smallest number.
I thought the best way and easiest to do this was making a single input form taking the input(left) and making the result(right). Making him use xxxx/xx/xx/xx/xx/xx as the format.
2009/08 = 2009-08-01 00:00:01
2009/08/01 = 2009-08-01 00:00:01
2009/08/01/05 = 2009-08-01 05:00:01
(adding one second as default otherwise it will be the day before)
I tried first by exploding the input into an array and validating each date section with regex. it got messy real fast and I can't figure out how to validate the proper ranges, say, /[1980-2009]/ or /[01-12]/ (that doesn't work like I expected). Also /[(0-9){2}]/ isn't going to work for the month obviously.
Another option is making each date section a separate select field. Making each field after month optional. But that gets messy in the html output, also given that each month doesn't have 31 days, I would need some javascript to change the day field depending on what month is selected. That's too much. It also seems a lot easier and faster to use a single field.
What do you guys suggest is the best way to input and validate custom datetimes?

I would reccomend calling strtotime() on the date, that way he can enter a variety of date formats, including month/year, day/month/year, day/month/year hours:minutes, and year-month-day hours:minutes
If strtotime can't determine what the date is, it returns false (or -1 in older versions of PHP, check your manual). SO your general code would be:
Run input through stripslashes (if needed) and strtotime
Check if value is === false. If so, display error
Otherwise, format the time as yor database expects is using date()

Related

Storing date and time in MySql

I have a form in which I ask users for a starting date and time, sometimes a time isn't required so I seperated the fields into start_date and start_time where start_date is of type date and start_timewas a varchar but I feel that a time field is more appropriate.
So, what is the best way to store these fields in terms of flexibility and the ability to concatenate in the future?
Or is it a more standard practise to have a single field and combine the two values given by the user?
and start_timewas a varchar but I feel that a time field is more appropriate.
Yes, definitively. As soon as you need to perform some sort of “time operation” on the value at any point, like say add or subtract a certain amount of minutes, VARCHAR would become a hassle.
Or is it a more standard practise to have a single field and combine the two values given by the user?
Since the time is optional, I think you should store it separately - otherwise, how would you distinguish between a record that doesn’t have a time, and one that has it coincidentally say 00:00:00 in the time portion of a full datetime? You can NULL your separate time column, but you could not make “part” of a datetime value NULL.
You can use the below code to enter date and time in mysql database.
<?php
$db=mysqi_connect("localhost","username","password","database_name");
$date=date("Y-m-d H:i:s");
mysqli_query($db,"insert into table(Date_Today)values(''$date')");
?>

Laravel update database if date matches today

The user is able to enter the amount of rain collected each day, by entering the amount of rain collected, and date. They should be able to enter rain collected in the past as well (by giving another date if needed).
So, how can i check (by using the created_at row) if the user has already entered some data for the current date? And if they have, update the value given for the specific date. I already know how to update etc, I just need a way to validate the date given.
I was trying to figure something out by using Carbon, But my head is about to explode, I can't seem to wrap my mind around this issue.
'created_at','>=',Carbon::today())
I know that wont work. The created_at looks like this:
2014-07-16 20:42:38
So I would need a way to check the current date, and skip the time/clock? How would my approach be on this?
Create your condition in query like below, to match only date in yyyy-mm-dd, to check the current date.
->whereDate('created_at','=',Carbon::today()->format("Y-m-d") )
Carbon::now()->toDateTimeString();
See how you can work with dates

Insert current date to MYSQL table, then echo back

It seems like there are too many complicated ways of doing this, so I'm looking for a clean, succinct answer to this issue.
I write a blog, I click submit, and the title, content, and timestamp INSERTS INTO my blog table. Later, the blog is displayed on the blogindex.php page with the date formatted as MM-DD-YYYY.
So this is my 3 step question:
What is the best column type to insert the date into? (ex: INT, VARCHAR, etc)
What is the best INSERT INTO command to use? (ex: NOW(), CURDATE(), etc)
When I query the table and retrieve this data in an array, what is the best way to echo it?
I'm new at PHP/MySQL, so forgive me if I don't know the lingo and am too frustrated reading 1000 differing opinions of this topic that do not address my issue specifically, or only cover one of the 3 questions...
Here is my opinion on your three questions:
Use the correct data type: Date or DateTime. I would choose for the DateTime type as you store the time as well (might be very handy if you want to have some kind of order, when you added the posts).
It all depends whether you just want the Date (use CURDATE()) or the Date + Time (use NOW()).
You fetch the data and format it how you want it. Don't format it yet in the query, just use the correct PHP functions for it (for example with DateTime). How you fetch the data, doesn't matter too much; you can use PDO or MySQLi or ...
Always store and process dates and times in UTC and perform timezone adjustments in your presentation layer - it considerably simplifies things in the long-term.
MySQL provides a number of different types for working with dates and times, but the only one you need to worry about is DATETIME (the DATE type does not store time information, which messes up time zone conversion as information is lost, and the TIMESTAMP type performs automatic UTC conversion (which can mess up programs if the system time zone information is changed) and has a smaller range (1970-2038).
The CURDATE() function returns only the current date and excludes time information, however this returns information in the local timezone, which can change. Avoid this. The NOW() function is an improvement, but again, returns data in the current time zone.
Because you'll want to keep everything in UTC you'll actually want to use the UTC_TIMESTAMP function.
To return the value you'll need to execute SQL commands in sequence with variables, like so:
SET #now = UTC_TIMESTAMP()
INSERT INTO myTable ( utcDateTimeCreatedOrSomething ) VALUES ( #now )
SELECT #now
Date would probably be the best type, although datetime will work as record more accurate as well.
There isn't a 'best insert into', but what do you really want and how accurate you want the date to be. For a blog, I would say make it datetime and use NOW(). so visitors can see quite accurate of when this post is made.
surely you can easily find huge to run sql and fetch a select query from sql using php by google, so I'll leave this easy work to your self.
For echo the date, you can use the php date format such as:
$today = date("m-d-y"); // 03-10-01
I think Styxxy has it pretty well right, but here is a links for your PHP date formatting part...
How to format datetime most easily in PHP?
(Supporting link: http://php.net/manual/en/datetime.format.php )
Basically it's
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))
... although, I think the strtotime is unnecessary as it should already have the type of datetime.
In terms of the MySQL, yes, do it as a datetime col, use NOW() as the SQL keyword, and depending on how you want to get it from the database you could...
SELECT CAST(col_name AS DATE) .... or .... SELECT CAST(col_name AS DATETIME) <-- this last one is implied due to the col type.
good luck! :)

How to prepare data to be inserted into MySQL DATE field?

I have 3 dropdowns on a form for the user to choose their birthday. One for date, one for month and one for year.
Right now I cam preparing the date given by the user like this:
$date = sanitize($_POST['year']).'-'.sanitize($_POST['month']).'-'.sanitize($_POST['day']);
and inserting $date into the database in a DATE field. I want to be able to do operations based on this field's values, like sorting by date etc...
Is this the right way to prepare the data or should there not be any hyphens?
According to the MySQL manual page on DATE, the proper format is 'YYYY-MM-DD', so this appears as if it would work and allow you use all of the MySQL date and date comparison operations and functions.
However, you should consider validating user input before sending it to the database (never trust the security or validity of user input). Maybe you should run it through PHP's date() to make sure that the date you are inserting is valid:
$date = date('Y-m-d', strtotime($_POST['month'].'-'.$_POST['day'].'-'.$_POST['year']));
I agree, I would convert the text using strtotime, then validated it, although you have 3 dropdowns maybe a data like Feb 30 might throw things off.

MySQL datetime into PHP

I have found a proper solution to my "problem" but even after reading mysql pages, I don't understand the logic behind it.
I currently store registration information in my system in a "datetime" formatted field in one of my tables (YYYY-MM-DD hh:mm:ss).
When I want to display the data on one of my php pages, simply posting the exact field data shows the format mentioned above.
I would THINK simply using date("Y-m-d",$row["DATE"]) where $row["DATE"] corresponds to the particular row value would return the desired format.
Instead I have to use:date("Y-m-d", strtotime($row["DATE"])).
Why is this? My $row["DATE"] field is not a string in the first place. Should I be able to simple rearrange the data stored in a datetime field? Wasn't that the purpose of rebuilding my entire tableset to accomodate datetime?
MySQL has a built in function called date_format which you can use to display the date how you want to.
SELECT DATE_FORMAT(date_field, '%Y-%m-%d') as date_field FROM table_name
The manual has the list of formats and the variables needed to display it that way. Using this method there will be no need to have PHP convert it etc. Plus it is less code on PHP side for something MySQL can handle easily.
EDIT
Sorry, just read you were looking for an explanation.
PHP's date function takes in a UNIX timestamp, which MySQL is not using. MySQL uses a real date format IE: YYYY-MM-DD HH:MM:SS, as you know, this is to be compliant for years later. The UNIX timestamp has a limited range from something like 1969 to 2037 that it is valid for, which makes it really useful for "timestamping" of items such as a chat box message or items they are not expected to be around post those dates, where as the MySQL DATETIME should not die out until the year changes to 5 digits or the world ends.
Read the WIKI on UNIX timestamp for more information on it.
MySQL does allow you to select dates in unix timestamp format, which allows them to be used more easily in PHP, exactly as you requested.
The previous answer seemed to ignore this point, or downplay it due to the range restriction on the unix timestamp, but if it's what you're looking for...
SELECT UNIX_TIMESTAMP(datefield) as u_datefield FROM table
will give you the date in timestamp format, which you can use as you suggested in PHP:
<?php
$showdate = date("Y-m-d",$row['u_datefield']);
?>
As the previous answer suggests, unix timestamps do have a limited range, so if you need dates prior to 1970 or after 2038 it may not be suitable, but for everyday use today it's great.
The main advantage of using timestamps over date strings is that timestamps can be added and subtracted, which is much harder with a date in string format.

Categories