How to set the current time as static variable using PHP? - php

I need to set the current date and time in static variable.
I need to insert the 50 records into database table. Here,I need to insert the current date and time. Then, I need to set the current date and time of the 50 records are same. I used this date('Y-m-d H:i:s'); format. This format will change every minutes and seconds.
How to I do. Please help me.

$date = date('Y-m-d H:i:s')
then use this variable,for create records. All records will have same time.

It's been a long time, but I found a simple solution. Maybe it's useful for someone (like me) that wants to do the same thing nowadays.
Even when you store the current time/datetime to a variable, the time it's still running, so it changes every second.
I solved it by storing the time() value into a MySQL table (datetime type of course), so the captured time will be stored as it is and stop running and changing every second. Then, when I want to use it, I just make a query from the MySQL table.
It's a simple way (for me) to capture the "now" value and make it stop running, but maybe there's a better way.

Related

Inserting actual hours (not time) to MySQL

I am trying to insert actual hours not the time itself to MySQL database through form fields. So for example
$time1 = '00:00';
$time2 = '27:20';
$time3 = '00:45';
So I can retrieve the different rows and can calculate on the fly whenever require. Either through search query or even in other area of the system.
When I have tried to do addition of above three times, it is not giving the result the way I am looking for
$total = strtotime($time1) + strtotime($time2) + strtotime($time3);
echo date('H:i:s', $total);
The result
14:16:44
While it should be something like
28:05:00
I have used TIME DATATYPE in MySQL table. I may use as a TEXT but I am also concern about the error happen in user input. Where I do not have to force the user to insert the any particular format but they can either insert as below way
27.20
27:20
or
1.5
1:30
My main concern is to calculate the time, the user input can be on second priority but it would be great if can implement.
So is there anyway, idea or hint to achieve this?
date() expects the timestamp in UNIX format, i.e. seconds since January 1 1970 00:00:00 UTC (which is also the value provided by strtotime)
You're passing it the result of adding a series of amounts of time since 1 January 1970 instead of just adding up hours, so (as far as date is concerned) you're generating a random date and time, and printing only the time (try printing the date of $total and see what you get).
Since your time is stored in the database, one possibility is to let MySQL handle the time calculations itself, e.g.:
SELECT ADDTIME('00:00',ADDTIME('27:20','00:45'))
will result in "28:05:00". You can have your database fields as TIME and operate on them directly through SQL, and do the user input conversions into acceptable TIME values in PHP.
If you're only interested in the hours and minutes, why don't you just store the value as an in integer? Just multiply the hours by 60.
You can handle the conversion in PHP.
Alternatively, you can also easily use two (very small) int fields for this.

Getting Current Time/Date - Saving To SQL Database

I have an application that posts to an PHP script, I want the PHP script to basically grab the current time and date, and insert it into my SQL database.
I'm currently doing this by using '$time()' within PHP, and then passing that into my SQL DB. In order to retrieve the time and date back, I use 'gmdate("M d Y H:i:s", $time);'.
I have a few questions though:
When I test this, the time it saves is an hour behind, so how do I apply different time zones? (I'm currently London/England) - but that might not be the case for the user who use this application.
Where is PHP retrieving the time from? Is it local? From the server?
Within my SQL, what should I set the data type to be? Timestamp? Currently, I've set it to varchar - but with all these different date and time types, I'm not so sure? (Date, Datetime, Time, Timestamp).
This PHP is called every time the user opens the application, so I want to be able to see: 'ah, so I see this user opened the application up at 21:20 on Wednesday the 14th'.
I'm sorry if its a noob question, but theres so many time and date classes and functions for both PHP and SQL that my brain has over loaded!
For a start, PHP time gets it's time from the server it's running on.
But if you really want the time a record was inserted, you should do one of the following:
Create a field in the table of type datetime, and set the default to:
GETDATE()
This will set the time automatically without you having to do anything special.
If you need that at time of input, still use SQL:
update [tablename] set LastUpdate=GETDATE()
Doing it this way ensures that the time is exactly when the record was set.
The PHP Time() function returns the EPOCH time (Seconds since January 1 1970 00:00:00 GMT).
You can use date_default_timezone_set() along with strftime() or mktime() to convert this to the servers local time.
You could set this via your application for the user if they're in a different timezone.
I linked the PHP manual pages for each function listed above.
What about to create a DateTime Field on MySQL table Structure and use MySQL to grab and set the date with NOW()?. Let MySQL do most calculations, it will help you to optimize the response time of your PHP script.
Look into this example: http://www.w3schools.com/sql/func_now.asp
Following the example of that page, but for an UPDATE:
UPDATE orders set OrderDate=NOW() WHERE OrderId=9999
Setting Timezone will fix the issue. I guess.
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";

How to get MySQL's CURRENT_TIMESTAMP in PHP - CodeIgniter?

I'm looking for a way to get the CURRENT_TIMESTAMP returned from MySQL, and ultimately, I want to construct a DateTime($with_the_result); in PHP (CodeIgniter), and compare it with a MySQL timestamp, using the function in this accepted answer. (Of course, changing the 3rd line)
I don't want to use PHP's DateTime(); to initialize it because my PHP server (Apache?) always have the wrong values. Although MySQL could be wrong too, I just want consistency. So I want to make sure that I get 'NOW()' in PHP
How can I do that with CodeIgniter & MySQL (and maybe Active Record? not necesssarily).
I will also appreciate any comments about the difference between timestamp and datetime, and which one should I use for big databases. I just need precision up to seconds.
Thanks for any help !
Turns out I can do this :
echo $this->db->query("SELECT NOW();")->row_array()['NOW()'];
which prints the timestamp : 2014-01-25 20:22:34
Timestamp is the number of seconds passed since 1970, and date time is pretty much the date and time down to the second.
If you're trying to get the current timestamp I'd suggest using
$current_timestamp = time();
In PHP it will return the current timestamp whenever it is ran. You would then just subtract the timestamp from MySQL with the $current_timestamp;

A server-bound counter in PHP that would reset to zero every midnight or at least would seem so

I'd like to know the best way to implement in PHP a counter that, having been incremented by some events on the server during a day, would be reset to zero with a new day coming, i.e at midnight. Probably comparing the date associated with the last value of the counter with the current date would make it reset?
EDIT: What if the counter gets reset the moment when it's going to be incremented provided that the code somehow figures out that the last time the counter was incremented was yesterday or a day earlier? It would be good enough.
Are you storing your counter in a database? If so, you might just want to store the date of the last change along with it. Let me assume you have a table counters(name, value, date), then the following pseudo-code might give you an idea:
$counter_id='herpderp';
$today = date('dMY');
$date, $value = query("SELECT date, value FROM counters where name='$counter_id'");
if ($date!=$today) {
$value = 0;
query("UPDATE counters SET date='$today', value=1 WHERE name='$counter_id' AND date='$date'");
} else {
query("UPDATE counters value=value+1 WHERE name='$counter_id' AND date='$date'");
}
echo $value;
Depending on your server you're either going to either be able to implement a Scheduled Task (Windows) or CRON Job (Linux). This will be what allows your script to execute at a specific time of day (or night).
As for the counter, you can implement that in a few ways. For data integrity and security, I'd store the value in a database. To increment, fetch the value and increment it (there are also some ways, depending on your DBMS, to do this with a single SQL query). Otherwise you could always edit a configuration file with I/O commands in PHP.
Setting up the CRON Job / Scheduled Task
If you give me more information on your server configuration I can give you specific tutorials on where you can find out how to set up your task.
Once you've figured it out, you'll want to call a specific script. Your script in PHP can be set up as follows:
Compare the current D/M/Y to the previous days, most likely stored in your database or configuration file. If this checks out, update your database/file performing whatever analytic actions you deem fit.

Adding values to a Timestamp

I am trying to create a script for quiz. I have stored current timestamp in MySQL DB as quiz start time, and want to check after each quiz how much time is left.
I have the idea that I will add 30 mins to saved time stamp and subtract this value from current time. That will be the time left. But I don't know the exact way of doing this.
My time stamp is saved in DB in format 2010-08-24 20:08:59. Any one have the idea.
Please let me know if someone have done it, or know how to get it.
Adding 30 mins to time stamp and showing the user how much time is left.
I am using the now() function to store the timestamp in DB.
Thanks
I would personally store the output of PHP time() in the database.
If you a human readable format from this value, you could use date('Y-m-d H:i:s', $fromdatabase);.
You want to store an actual UNIX timestamp in the database, not a string in that format.
You may or may not be doing this already, it depends on the type of column you're using. For MySQL, you should be using TIMESTAMP, which allows you to retrieve the timestamp with
SELECT UNIX_TIMESTAMP(column_name) ...
To store the current time + 30 minutes, all you have to do is:
INSERT INTO table (column_name) VALUES(UNIX_TIMESTAMP() + 1800)
You can know if the time has expired by comparing time() against the value of the column.

Categories