Insert current date to the database? - php

How do I insert the current date to my database? I have a column called date to put it on.
I want to insert it at the same time I insert this:
$sql="INSERT INTO `Lines` (Text, PID, Position)
VALUES
('$text','$pid','$position')";
Is there a way to automate it in PHPMyAdmin or it's the same to do it this way? Thanks

If the table definition has the timestamp column default set to CURRENT_TIMESTAMP, you actually don't have to do anything at all. Otherwise, NOW() and CURRENT_TIMESTAMP will work, as in:
INSERT INTO t1 (timestamp_column) VALUES (NOW());
There is a difference between CURRENT_TIMESTAMP and NOW() but it's probably too small to matter to you.
phpMyAdmin seems like it has CURRENT_TIMESTAMP as an option when creating a new column.

INSERT INTO `Lines` (`date`) VALUES (NOW());

Depending on your requirement, you can also do this
$date=date('d.m.y h:i:s');
And then insert $date. I mean if you only want to view the date & time. Otherwise i also recommend time().

Otherwise... if you're using an integer, as is common in PHP, just use time() and insert it's value the same way you inserted the other variables, or use MySQL's UNIX_TIMESTAMP()

The best way to store timestamps is as UNIX timestamp integers in GMT / UTC. This allows you to always know the exact time no matter where you, your server, or your users are located. A bonus is that you can allow your users to set their timezone and display times meaningful to them.
$sql = "INSERT INTO `Lines` (`timestamp`) VALUES ('" . time() . "')";
or
$sql = "INSERT INTO `Lines` (`timestamp`) VALUES ( UNIX_TIMESTAMP() )";
Be careful if you choose to use NOW() or CURRENT_TIMESTAMP as they are managed by the database server and it's settings. If the server your site is hosted on is in one time zone and you move to another host in another timezone all of your timestamps will be incorrect. Using Unix integers will add a little extra effort wherever you application deals with times but it gives you the most accuracy and the most flexibility.

Related

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 - Putting a date into a MySQL table

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'))

Save date/time from PHP to SQL

I want to save the date and time from PHP to SQL. Here is the SQL statement to insert new record (found in a method within a class):
INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
value (:headline, :text, :date, :rating, :product_id, :username)
And in my .php page, I call the current date and time using $_SERVER['REQUEST_TIME']. But still I'm getting the error "Incorrect datetime value". What can I use to get the date?
Your timestamp can be generated:
$timestamp = date('Y-m-d H:i:s');
This should mimic the mysql timestamp and datetime formats.
Assuming that the mysql has its timestamp synchronized with the php server in question, you can also just use the mysql current timestamp functions:
NOW() or CURRENT_TIMESTAMP or CURRENT_TIMESTAMP()
Does it have to be the exact request time? You could make your life easier and simply use:
INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
value (:headline, :text, now(), :rating, :product_id, :username)
MySQL inserts the current date as soon your entry is written to the table.
it is only a guess, but $_SERVER['REQUEST_TIME'] returns a float, not a valid datetime format.
If you need the current time you can do it like that:
INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
INSERT INTO tbl_reviews ('$headline', '$text', CURDATE(), '$rating', '$product_id', '$username');
date_default_timezone_set('US/Eastern');
$cur_date=date("Y-m-d");
You can use SQL's own CURRENT_TIMESTAMP value to get an automatically formatted timestamp.
As for $_SERVER['REQUEST_TIME'], you can just use time() or microtime() instead.
As mentioned, REQUEST_TIME, as well as time() and microtime() return a UNIX timestamp, which is basically the amount of seconds that have passed since the UNIX epoch, which is not the same format as a DATETIME field expects.

Add date to mysql from php for sorting later

when inserting a date into a MySQL DB using PHP what is the best format so that I can sort by date later. I started using
$current_time = date("Y-m-d");
Is this the best practice?
If you are able to control your database fields then I would recommend using MySQL's built in Timestamp data type. You can set it to the current time by default.
CREATE TABLE IF NOT EXISTS `your_table` (
`date` timestamp NOT NULL default CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
If not then I would reccomend just storing the default PHP Unix formatted timestamp in an integer field.
$current_time = time();
The database handles dates internally for storing and sorting. Y-m-d format is good
You do not ever need to generate the current date or time in PHP to insert it into a query. Use the MySQL constants CURRENT_DATE and CURRENT_TIMESTAMP in the query instead.
INSERT INTO table (name, date) VALUES ('Bob', CURRENT_DATE)

datetime function in php

I want to store the data and time in my MYSQL db.I have a datetime field in my db
I want to store current datatime in my db
How shold i get the current date time?How to pass it to db via a sql query
How can i then retriev an print it in correct yyyy--dd--mm format or any other format
What wil be format of time? wil it be 23 hrs etc?
How do i print date and time?
You can let MySQL determine the current timestamp by using Now() in your query.
INSERT INTO foo (dtfield) VALUES (Now())
This can also be done with a default value for a TIMESTAMP field in your table definition
CREATE TABLE foo (
id int auto_increment,
creationTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
v int,
primary key(id)
)
You could use MySQL's built in date/time functions if you only want to insert it into the MySQL database.
Have a look at: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
Otherwise, you can use the PHP's date() function.
Assuming table named 'items' and field named 'modified' of type 'timestamp'
$r = mysql_query("INSERT INTO items (modified, x, ...) VALUES (CURRENT_TIMESTAMP, $x, ...)");
// (or "UPDATE items SET modified=CURRENT_TIMESTAMP, x=$x, ...)
...
$r = mysql_query("SELECT UNIX_TIMESTAMP(modified) FROM items");
$item = mysql_fetch_assoc($r);
$formatted_ts = date('g:ia', $item['modified']); // or another format *
you'll need to add appropriate error-checking which I've omitted; also need to adjust for consideration of timezones, which I've also left out
see date()
You might also want to set your timezone.

Categories