PHP - Putting a date into a MySQL table - php

I have what is most likely a very simple question.. I am designing a simple blogging system and I am trying to put the current date into the table where the blog post is stored whilst waiting for administrator approval. but the method I have used puts 0000-00-00 into the date column! What I am using is as follows:
$query = "INSERT INTO blogentry VALUES ('".$mnam."','".date('d-m-Y h:m:s') ."\n"."','".$mcom."','".$approve."')";
I am relatively new to php so stumble accross errors like this all the time... but I cant seem to google this one!
Thanks guys!

So the easiest way to do this is just let MySQL handle it with the NOW() function:
INSERT INTO blogentry VALUES( ..., NOW(), ... )
Another option is to use TIMESTAMPs by changing your table - set the column to type TIMESTAMP with DEFAULT CURRENT_TIMESTAMP, and you can just ignore that column when inserting - it will automatically be filled with the current time. You will need to specify the columns you're inserting to in order to skip a column:
INSERT INTO blogentry( column1, column2 ) VALUES( column1value, column2value )
Finally, you NEED to sanitize your inputs. Preferably using prepared statements and PDO (http://php.net/manual/en/pdo.prepared-statements.php), or at least using mysql_real_escape_string.

From the MySQL manual on DATE, DATETIME
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The
supported range is '1000-01-01' to '9999-12-31'.
This means you have to insert the dates in YYYY-MM-DD format. You are using date('d-m-Y h:m:s') format. Change that to date('Y-m-d') and it should insert correctly.
If you want the time as well, then you need to change the column datatype to DATETIME and then insert using the format date('Y-m-d H:i:s').
As other mention, you can use an INT column type instead and store a Unix timestamp which is stored in UTC so it is more portable. You can then easily manipulate the timestamp to output the date any way you would like.

Try just storing a strtotime() result. It creates a unique timestamp, which can then be parsed however you need it in the future.

You might need to give the timestamp to the date function:
date('d-m-Y h:m:s', strtotime('now'))
Also, to do a standard datetime format:
date('Y-m-d H:i:s', strtotime('now'))

Related

error in save date in database with php

want to be able to store the current date from PHP in to a mysql table.
$date = sprintf("%'04s-%'02s-%'02s",$year_number,$month_number,$day_number);
$sql="INSERT INTO `prg omran`.`paid`(`Comapny_id`,`Amount`,`Date`,`Creditrecord`) VALUES ('".$ID."','".$credit."','".$date."','".$yes."')";
Date's column type in database is DATE.
but date save in database like this: 0000-00-00
help me.
try this
$date = sprintf("%'04s-%'02s-%'02s",$year_number,$month_number,$day_number);
$sql="INSERT INTO `prg omran`.`paid`(`Comapny_id`,`Amount`,`Date`,`Creditrecord`) VALUES ('".$ID."','".$credit."',".$date.",'".$yes."')";
or
if you want to inset today's date use
$sql="INSERT INTO `prg omran`.`paid`(`Comapny_id`,`Amount`,`Date`,`Creditrecord`)
VALUES ('".$ID."','".$credit."',curdate(),'".$yes."')";
I need to store Date field in database for example VARCHAR(10) becouse, DATE type in mysql server don't support persian (farsi) date.
If you are getting the current date, just use one of the built-in MySQL functions for that:
$sql="INSERT INTO `prg omran`.`paid`(`Comapny_id`,`Amount`,`Date`,`Creditrecord`)
VALUES ('".$ID."','".$credit."',curdate(),'".$yes."')";
You won't ever have to worry about formatting or any sort of funny inputs and you can still do all sorts of addition, subtraction and the like using one of the many other functions.
Edit: I have just looked up some information on the date system and you will run into problems trying to squeeze that data into a date field. The first six months have 31 days, the next 5 have 30 days, then the last has 29 - unless it is a leap year in which case it has 30. The date field simply won't LET you insert these values into a date field.
You might need to convert your data to a timestamp and write a function to encode/decode it into the format you need.

what is the format with which mysql stores date and time?

While creating a table, I defined one column of DATE type and one of TIME type. As I insert the values using a php script like :
date--> 2013-11-11
time--> 12:12:12
and when I query the sql browser I see those values in exactly the same manner. But I am unaware of the format with which it stores the date and time. Like yyyy-mm-dd or yyyy-dd-mm.
Is there any way I change it ?
Dates and times are stored in MySQL in the format "YYYY-MM-DD" and "YYYY-MM-DD HH:MM:SS" which is not necessarily the format you want to display in your web page or application. There are two methods to reformat the date and time into the desired format. One is to do it in the SQL query in MySQL calling the DATE_FORMAT() function and the other is to do it with the programming language retrieving the data from the MySQL database.
From MySQL 5.1:
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The
supported range is '1000-01-01' to '9999-12-31'.
For second question: you can't change default DATE format for the storage, please see this question also
http://dev.mysql.com/doc/refman/5.5/en/datetime.html
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format
http://dev.mysql.com/doc/refman/5.5/en/time.html
MySQL retrieves and displays TIME values in 'HH:MM:SS' format
I do not believe this can be changed. But you do not care. You can extract dates and times in the format of your liking with the DATE_FORMAT() and the TIME_FORMAT() functions.
If you want to know the internal storage of Date columns, you can check Date and Time Data Type Representation, but I think you want to select date in different format; which other guys already answered about it.
It is stored in 3 bytes, and it is always YYYY-MM-DD.
The datetime is in Y-m-d H:i:s format, or year month day and hour minute second. If you only use a part, the format stays the same.
If you want to change the format there are many ways. The easiest would be to do something like return date("Y-d-m H:i:s", strtotime($mysqldatetime)); (will turn it to dutch date);
Keep in mind that you are using two seperate columns, one for time and one for the date. If you use only one column the missing values are filled with default values (time would be 00:00:00 and date would be 1970-01-01

PHP, using timestamp for mysql?

I've been trying to search for a straight answer, but for some reason the answer isn't coming to me. I was wondering what is the best way to store date/time into mysql?
I researched that timestamp in mysql is good because it will update depending on timezones too.
So I've set my column name as timestamp with datatype in mysql to timestamp, but what is the best syntax for storing current date/time to that?
"INSERT INTO table(timestamp) VALUES(now())" //or use timestamp()? or is there such thing?
?
Please help, thanks!
You could use datetime datatype in your table and just store it as NOW() which will store it as YYYY-MM-DD HHHH:MM:SS
Here are some considerations:
Set the column type to BIGINT so you can store 64-bit timestamps
You can insert using the PHP time() function, or MySQL's UNIX_TIMESTAMP() function
Name your column something other than timestamp. It is a permitted word1 see last section, but its also a type in MySQL.
If you store times as a Unix timestamp in MySQL, they are stored in UTC which makes dealing with timezone conversion very easy. In a 64-bit environment, PHP can handle dates up to the year 219,250,468.
Both of these queries are the same:
INSERT INTO `table` (`time`) VALUES(UNIX_TIMESTAMP());
// or
$time = time();
INSERT INTO `table` (`time`) VALUES($time);
Then to display it in PHP:
SELECT `time` from `table` WHERE `id` = 1;
echo date('Y-m-d H:i:s e', $row['time']); // 2012-07-31 23:59:59 America/Los_Angeles
Whatever timezone is set in PHP date_default_timezone_set() will be the timezone used when you output the date in PHP.

php timestamp utc

I have a PHP MySQL query that inserts some data into a MySQL database and it includes a timestamp.
Currently the INSERT query uses NOW() for the the timestamp column and it is saved in the database in the following format: 2012-07-24 13:13:02
Unfortunately for me the Server is not in my time zone and it is listed as America/Los_Angeles as shown print date_default_timezone_get();
I was hoping to do the following:
date_default_timezone_set('Europe/London');
$timefordbLondonEU = date('Y-m-d H:i:s', time());
and simply save into the database the $timefordbLondonEU in place of the NOW();
Is this a good way to save such data ?
Many Thanks,
Richard
[ADDED TEXT]
I changed the Type in the MySQL db to DateTime and did the following:
date_default_timezone_set('Europe/London');
$timefordbLondonEU = date('Y-m-d H:i:s', time());
It is working but Im still not getting the overall concept yet.
Assumptions based on your comments:
MySQL = Does not have a datatype UTC you simply use type INT.
Unix_TimeStamp() will save the current time or count? in UTC format such as 1343247227.
As UTC is a count from a common 0 point you can get any timezone from it. Assuming that you don't want a date before the reference 0 point in 1970.
My guess and lead on from what you have said is the best way to do it is save the time as UTC in an INT (1343247227) and then generate any time zones you want from there. Again assuming you don't need to store dates before the reference 0 point in 1970.
Equally why not store as datetime YYYY-MM-DD HH:MM:SS at a known timezone and then convert to UTC or other timezones. It all seems pretty messy =(
As #Petah said in the comments, store your times in UTC and covert them in the application as needed.
Unix timestamps are in UTC so I usually store my times in the database as timestamps. This saves the headache and confusion of first converting to UTC to insert, and then from UTC when selecting.
That is, make your time field an INT type, and use the function UNIX_TIMESTAMP() in MySQL when you insert, or get the timestamp from PHP using the time() function.
When you fetch the timestamp from the DB it will be in UTC, but when you display it in your PHP application using date(), it will display in the server timezone, or whatever you set with date_default_timezone_set.
Therefore the following two queries will work:
INSERT INTO `table` (id, time) VALUES(NULL, UNIX_TIMESTAMP());
// or
$time = time();
$query = "INSERT INTO `table` (id, time) VALUES(NULL, $time);
If you want to select it from the DB as a DATETIME, you can do this:
SELECT *, FROM_UNIXTIME(time) as dt FROM `table` WHERE 1
The resulting dt column will be in the format yyyy-MM-dd hh:mm:ss.
You can format the numeric timestamp in PHP using date()
If the PHP version you have is 64-bit, you aren't limited to the 1970 - 2036 range, PHP will support 64-bit timestamps, just make sure to use a BIGINT column in MySQL in that case.
Hope that helps.

Set current time field for MySQL

I am trying to set the value of a field via a hidden form field to the current date and time using either PHP or Javascript that would conform to MySQL's datetime field.
You can use PHP to get and format the current system date/time for use in MySQL like this:
$now = date('Y-m-d H-i-s');
You can directly set current date and time in your SQL insert query using NOW():
INSERT INTO table_name (current_time, column2, column3,...)
VALUES (NOW(), value2, value3,...)
where current_time is the field where you want to put current date and time.
Create the column using DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP
Those together will make it so that any new rows inserted have the current time and are updated again when the column is updated.
Example:
CREATE TABLE test (last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)
Edit: Nevermind, this will use a TIMESTAMP column, not DATETIME. Other answers will do what you want.
<?php echo time(); ?>
will output a nice simple integer number that you can pass directly into MySQL and convert into a native mysql datetime value with FROM_UNIXTIME(). It'll save you the trouble of formatting the data in a nice YYYY-MM-DD hh:mm:ss string.
$current = date_timestamp_set(date_create(), time());

Categories