Get value of NOW() in MySQLi PHP - php

Assume that your webserver is detached from your database server. Their clocks might not be properly synchronized (down to milliseconds etc.).
You perform an insert such as "INSERT INTO sometable (VALUE,VALUE2,DATETIME) VALUES ("something","something else",NOW());"
Is there any way to get the timestamp generated by MySQL back into PHP? In the same fashion as when using $sqlObject->insert_id to get the AUTO_INCREMENT value of the last inserted row.
Edit:
I realize I could just use the insert_id and run a SELECT to get the timestamp, but this would require that I run another statement. I am wondering if it is possible in a single statement.

You can not get the direct value but you can do it via 2 ways.
1) Make a select query like select now() as cur_time. and take its value and use in the 2nd query. [ Its possible that you might get different time for this solution, SO i will suggest not to go with this solution and better you go with option 2. ]
2) After inserting the data get its ID and and make a query and get the inserted date time.
If your PHP and MYSQL server date time are same then you may use php's date function to get the current date / time .

Related

MySQL and PHP TimeZone

In my PHP.ini file I set the TimeZone like so...
'America/New_York'
so when i ran a simple php Date() function
echo date("Y-m-d H:i:s");
I get the Correct dateTime according to 'MY' system time as that's what i am comparing against and want to store in my MySQL db as well. (as reported from PHP).
Now the problem is, i exported a MySQL db to PDF format, just to see what it looked like, and the time was 1 hour back, ex.. it was (10:00 a.m.) here and the PDF footer said (9:00 a.m.)
So.. i got to thinking.. my PHP script will INSERT into the db the correct dateTime that i need.. But i have alot of dateTime comparing going on for accounts,
I know if i run any MySQL Queries in phpMyAdmin then i will get the wrong dateTime.
i have tried running in (phpMyAdmin SQL Query)
SET time_zone = 'America/New_York';
-and-
SET time_zone = '-05:00';
But when I run the query
SELECT ##global.time_zone, ##session.time_zone;
I get back SYSTEM and SYSTEM.
(I should also mention i am on shared hosting)
If I use the MySQL NOW() function in my query, the time entered into the db will be calculated by MySQL, according to it's own timezone.
like this..
mysql_query("INSERT INTO table (id, value, time_created)
VALUES ('{$id}', '{$value}', NOW())");
I understand that I will have to do all of my INSERTING and comparing in PHP to keep the times right.. but with the above, it will insert the wrong time.
so this is my dilemma...
But will this affect anything that i am not foreseeing? I just feel like somehow this will affect my times.
So how can I get around this or get MySQL on the SAME timezone? and make sure that ALL my date/times are right, not the 1 hour behind..
Two queries ran successively through PhpMyAdmin will be executed in two separate sessions (connections) therefore SELECT ##session.time_zone alone will always return "SYSTEM".
I doubt you can (and I hope you cannot) change the global time zone on a shared server, so always expect "SYSTEM" for SELECT ##global.time_zone. On the other hand you should be able to change your session's time zone.
Try running these two queries in one execution, it should show the new time zone :
SET time_zone = '-05:00'; SELECT ##session.time_zone; -- same session
NOW() returns time in the current session time zone, so time zone does matter. However I would rather store times in GMT time zone, but I suppose that's more a matter of taste.
Depending on what you may do and what you may not do (on your shared hosting) you could choose to either use the following statement as the start of all your queries: "set time_zone='-05:00';", for example: "set time_zone='-05:00'; select foo from bar;" or (maybe the most reliable option): only use timestamps in your tables and queries and create DateTime objects in PHP based on the timestamp you received.

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 execute a PDO query with a condition based on calculation

I work on a site where visitors can create an account, and to do so, they have to confirm their email adresses in the end of the process.
Before the account is created, the entered values such as email, pass etcetc are kept in a special table temporarily. That means a visitor has an hour to open their email and klick the link, or else that row will be deleted, to prevent "garbage" from bots and evil or simply overlazy people.
My idea was to let the users clean up the mess, and this is how: when a user klick the link sent to them, the row in the table with temporarily stored values is moved to the actual table for members, and another function will clean up rows that are "outdated", that is, who are inserted more than one hour ago.
This is my current code:
$stmt3 = $dbc->prepare('DELETE FROM temp_storage WHERE time() - time > 3600');
$stmt3->execute();
(time is the column with the time when the row was inserted is stored)
However this code is appareantly not working. I know I could do a workaround with SELECT FROM temp_storage and then check if the row is inserted too long ago, but I thought that, why would it be impossible to do it this way?
Now my question is, is it, or am I doing it the wrong way?
TIME() in MySQL does not give you the current time, it strips the "time portion" from a timestamp. You are looking for a different time function, probably UNIX_TIMESTAMP() if that is how you are storing your timestamps in the table.
Review MySQL date and time functions here: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
The function you're using to get the current time is not correct. It's not time() it's now().
If you check what $pdo->errorInfo() returns you'll see an error message.
In light of your comments about echo time() i get what you wanted to do but in order for that to work you should have written the following:
$stmt3 = $dbc->prepare('DELETE FROM temp_storage WHERE '.time().' - time > 3600');
$stmt3->execute();
By doing this you're using the return value of PHP's time() function to build a string which will then be sent to MySQL to be executed as a query.
You have to understand the difference between PHP-realm and SQL-realm code:
PHP only constructs text strings. It patches together various words an letters to compose a string. PHP doesn't even care what that string is for.
PHP can never look into that string and say "hey this is some good SQL queries right here".
What it can do is send the text you composed to an SQL server; the sql server will try and execute the text as if if were a corect SQL language statement.
If it hits errors it'll report them back to PHP if not it returns the results to PHP. In any case the SQL statements are strings and they get composed before being actually sent to the server.
"Interrupting" a string and concatenating another string to it such as "me"."&"."you" is just part of the process of building the string before sending it to the SQL server.
Try this:
$stmt3 = $dbc->prepare('DELETE FROM temp_storage WHERE UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(time) > 3600');
I assume the entry_dt column is a datetime column.
where CURRENT_TIMESTAMP - interval 1 HOUR > entry_dt
You should avoid naming columns the same as sql functions and keywords
ref
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

Question regarding MySQL timestamp comparisons

I'll explain my goal first: I want the user to query the database, and return rows only if those rows have been updated since their last query. No sense returning data they'd already have. So I created a column called 'lastupdated', a timestamp type which autoupdates every time any content in the row is updated. This works fine. Now, I want to form the query correctly. The user will have their previous query's timestamp saved, and via php will use it to compare their previous query's time with the time each row has been updated. If the row was updated after their last query, the row should be returned.
I made something like this,
SELECT * FROM users WHERE '2011-02-26 01:50:30' <= lastupdated
but its obviously much too simple. I checked the MySQL manual and found this page MySQL Time/Date Page. I'm sure the answer is here, but I've read through it any nothing really makes sense. I have a timestamp in the same format used by the MySQL timestamp type, but I don't know how I will compare them. Thank you very much for your help.
That query is exactly how you'd do it. As long as a stringified date-time is in MySQL's preferred format (yyyy-mm-dd hh:mm:ss), then it will be internally converted into a datetime value, and the comparisons will go ahead.
You'd only need the date/time functions you found if you want to do something more complicated than simple "greater/less than/equal" type comparison, e.g. "any records that have a December timestamp".
As Marc said, your code should work. But you probably want to do this programmatically with a variable for the time instead of the literal.
If you don't have the date-time specified as a string, but rather as a timestamp (e.g. from using the php time() function), then you can use the following query:
$query = "SELECT * FROM users WHERE FROM_UNIXTIME(" . $timestamp . ") <= lastupdated";
The key is the FROM_UNIXTIME() MySQL function.

Storing currentDate in database

I am using the NOW() function to store date in the database. But when i check the values in the database, the date is something else.
$sql="INSERT INTO feedback_comments
(posted_by, email, comments_text, comment_date)
VALUES
('$postedBy','$emailID','$message',NOW())";
Is it always off by the same amount? If so, it's likely to be either a configuration difference in times between your database and PHP environment, or even two different times if they're running on separate boxes.
The other possibility is that the type of the column you're inserting in to is not correct. In that case, you'll probably get something like 20071215235026.000000 instead of '2007-12-15 23:50:26'.
You can use current timestamp as the field type so with out insertion it will record the date time

Categories