How to get mysql data from table into php date()? - php

Title was wierd, yes. (Im norwegian)
Okay, I'm making a counter/timer to my new project and what it do is that when a user makes a action he/she must wait 100 sec before doing it again. But, how to get the timestamp (saved in mysql db) into the PHP code again and checking how long time since last time user checked to try again.
Some of my code (From the script):
// Waiting for time to go?
$sql = mysql_query("SELECT * FROM `crimes` WHERE user_id = '".$_SESSION["id"]."'");
$num = mysql_num_rows($sql);
$row = mysql_fetch_array($sql);
if($num == 1){ //Waiting
$time_now = date("H:i:s", strtotime("+100 seconds")); // This is where Im stuck, how to get that timestamp from mysql with 100 secs added?
$time_to_check = date("H:i:s", $row["time"]); // The time the action was done.
// This is where the code is going to check how long time since user visited.
} else {
}
So what Im asking for is that I need that one var that contains the data from mysql with 100 secs added, how? :)
This works:
$sql2 = mysql_query("SELECT UNIX_TIMESTAMP(time) AS time FROM `crimes` WHERE user_id = '".$_SESSION["id"]."'");
$row2 = mysql_fetch_array($sql2);
$seconds_ago = time() - $row2['time'];
$time_now = date("H:i:s", $seconds_ago + 100);

You can convert dates to UNIX timestamps in MySQL:
SELECT UNIX_TIMESTAMP(time) AS time FROM `crimes` ...
Then inside PHP:
$seconds_ago = time() - $row['time'];

$time = date("h:i:s", time() + 100);

$time_now = strtotime("now");
$time_to_check = strtotime($row["time"]) + 100;

Related

How should I make timer in PHP that can count timediff of the user form the last request?

Hey guys I am trying to make a counter that count for 10 min form that last time user pressed the button(for ex requested anything).
What I did, I took timestamp in Mysql and code is below.
$timequery =" SELECT NOW() AS cur, ( SELECT lastclaim FROM table1 WHERE id =".$id." ) AS mytime ";
if( $qry=mysql_query( $timequery ) )
{
$timer1 =strtotime( mysql_result($qry, 0,'mytime'));
$timer2 =strtotime( mysql_result($qry, 0,'cur'));
$timer = abs( $timer2 - $timer1);
return $timer;
}
Please suggest me better logic for this problem or guide me for improve this code.
IMUO i wouldn't go to ask at database, you could do it with SESSIONs and you will have less DB access. I.E you coud do something like:
$nowtime = date('Y-m-d h:i:s');
if(isset($_SESSION['timeOfLastAction']){
$timeOfLastAction = $_SESSION['timeOfLastAction'];
}else{
$timeOfLastAction = $nowtime;
}
$endtime = strtotime( $timeOfLastAction ) + 600; // 10 minutes == 600 seconds
if($nowtime > $endtime){ //10 min or more from last action
//do your stuff
$_SESSION['timeOfLastAction'] = date('Y-m-d h:i:s'); //reassing
}
If you need/want to store at database you could change the if{}else{} part to your actual code.. but you have to access to database, store value, update the value in each request, etc. you could use a mysql native function like:
SELECT * FROM table1
WHERE lastclaim <= NOW() - INTERVAL 10 MINUTE
AND id=$id
And you will avoid the data manipulation in PHP, you will recive a user only if the interval is >10 min.
Here a similar issue of yours: Adding 10 minutes to a date from mysql datetime and comparing it to the time now
I hope it helps!

PHP - Deduct two timestamps from each other, display in minutes

I have a mySQL database that stores the checkin and checkout time of a person in a gym. I have imported the checkin and checkout times in to my PHP script. Now I want to deduct the two timestamps from each other - giving me the time left. I want this to display in minutes.
This is my idea:
$checkOut = "2016-01-31 15:01:11";
$checkIn = "2011-01-31 15:32:35";
echo ($checkIn - $checkOut);
// I want this to display 31 minutes.
I have seen many examples on StackOverflow, but none matched my description and I couldn't reverse engineer the ones I found - because they use the time() function - which I guess takes the current time.
You can use strtotime();
$checkOut = "2016-01-31 15:01:11"; // initial value
$checkIn = "2011-01-31 15:32:35"; // initial value
$checkOut_stamp = strtotime($checkOut); // Converting to unix timestamp
$checkIn_stamp = strtotime($checkIn); // Converting to unix timestamp
echo date("i", ($checkIn - $checkOut)) . 'Minute(s)';
IMP Note: The above method will only work if the minutes are below 59, or else the hours will be rounded off and discarded. So if your requirements is showing the time in minutes which can be grater than 59 minutes eg. 144 minutes, then you'd want to just divide by 60, as follows.
$checkOut = "2016-01-31 15:01:11"; // initial value
$checkIn = "2011-01-31 15:32:35"; // initial value
$checkOut_stamp = strtotime($checkOut); // Converting to unix timestamp
$checkIn_stamp = strtotime($checkIn); // Converting to unix timestamp
$seconds = $checkOut_stamp - $checkIn_stamp;
if($seconds > 0){
if($seconds > 60){
$minutes = $seconds/60;
} else {
$minutes = 0;
}
} else {
$minutes = 0;
}
echo $minutes . ' Minute(s)';
$checkOut = "2016-01-31 15:01:11";
$checkIn = "2011-01-31 15:32:35";
$time = (strtotime($checkIn) - strtotime($checkOut));
echo date('i',$time);
use this code
If you were fetching this record from database then you can simply achieve it using MySql function TIMESTAMPDIFF, as no need to use PHP function over here
Select TIMESTAMPDIFF(MINUTE,checkIn,checkout) as tot_diff from your_table

countdown timer using php, can't make it work

i am making a php countdown timer that display only minutes and seconds.
here is my code:
$time = "10:00";
$time_min = substr($time, 0,2);
echo $time_sec = substr($time, 3) . "<br>";
$current = date("i:s");
$target = date("i:s" , mktime(0,$time_min,0,0,0,0));
echo $current-$target . "<br>";
echo $target;
the output should be the remaining time from the time the user opens the page.
Not knowing the details of your jQuery I am taking a shot at this.
I prefer working in seconds, so to get the $timeRemaining (you must know the initial time to do this) at any given instant in the 10 minute window, I would do this:
$targetTime = time() + 600; //you have to save this either in database or as variable somewhere
Then on subsequent opening of relevant php file the following code could be used if targetTime is saved in database
$sqlTime = mysqli_fetch_assoc(mysqli_query($cxn, "SELECT targetTime FROM timeTable WHERE id = '$myID'"));
$currentTime = time();
$timeRemaining = (($sqlTime['targetTime'] - $currentTime) / 60) . ":" . (($sqlTime['targetTime'] - $currentTime) % 60);

Return the difference between two (dates and time ) PHP

i tried most of what is available on stack overflow but none seem to work.
any way i am trying to compare two (date and time formats). and calculate whether their difference is within 5 seconds of each other
the first date is the current date:
$today = date("Y-m-d H:i:s");
the second date is taken from mysql database:
$result = mysql_query("SELECT * FROM BUS_DATA where BusRegID = 'bus'") or die(mysql_error());
$row = mysql_fetch_array($result);
$update_date = $row["update_date"];
the answer should be segmented into years , month , days , hours , minutes ,and seconds portions.
I am running PHP Version 5.3.3
Edit: most answers give result in time frame only , I want to check whether the date matches , then compare if the time of the day is within 5 seconds , than you guys in advance :)
Try this
function getTimes($t1, $t2)
{
$timeFirst = strtotime($t1);
$timeSecond = strtotime($t2);
$differenceInSeconds = $timeSecond - $timeFirst;
$h=0;
$m = floor($differenceInSeconds / 60);
$s = $differenceInSeconds % 60;
if ($m>=60)
{
$h = floor($m / 60);
$m = $m % 60;
}
$tim = $h.':'.$m.':'.$s;
return $tim;
}
it will return difference time in hours:min:sec
use strtotime, it's understands almost any date formats:
$timeDiff = abs(strtotime($today) - strtotime($update_date));
this gives you the difference between dates in seconds.
If you want to know whether it's within 5 seconds then use Timestamps, makes it into a simple int calculation.
$now = time();
$test = strtotime($update_date);
if($now - $test > 5) {
//NOT WITHIN 5 SECONDS
}

SQL query inside a loop in a loop

Hey everybody. I am trying to print out a schedule with thirty minute intervals and would like to query a DB to get whatever thing is happening at that time. If i manually enter the time (hour, minute, am/pm(months, year, day work as is)) i get events. It's just when i let the query pull the time from the loop this doesnt work. Any ideas?
$day = date('d');
$year = date('Y');
$month = date('m');
$start = mktime(0,0,0);
$thing_query="SELECT thing FROM things WHERE day='$day' AND month='$month' AND year='$year' AND hour='$hour' AND minute='$minute' AND ampm='$am'";
$result=mysql_query($thing_query);
for($min = 0; $min < 24 * 60 * 60; $min += 30 * 60)
{
$hour=date("h", $start + $min);
$minute=date("i", $start + $min);
$am=date("A", $start + $min);
while ($row=mysql_fetch_array($result)) {
$thing = $row[0];
}
printf("<tr><td>%s</td><td>$thing</td></tr>",
date("g:i a", $start + $min));
}
Variable references in a string are only valid at assignment; they don't continue to update if you change those variables, so when you do
$thing_query="SELECT thing FROM things WHERE day='$day' AND month='$month' AND year='$year' AND hour='$hour' AND minute='$minute' AND ampm='$am'";
it's equivilent to
$thing_query="SELECT thing FROM things WHERE day='15' AND month='2' AND year='2011' AND hour='' AND minute='' AND ampm=''";
because $hour, $minute and $am haven't been set, and thus the query returns nothing.
Even if they were, updating the string won't update the database query; you'll need to call mysql_query() on the new string to get that data.
If you move the $thing_query= and $res= lines to just before the while loop this should work, although it will only return the last event in each timeslot, because you're overriding $thing each time you go through the loop. It will also continue to list an event in every timeslot until it reaches a new one, because you're not clearing $thing.
As Andy says, this isn't currently a very efficient way to do what you want, but since you're presumably just starting out I'm guessing its more important to you for now that it works rather than being efficient, so hopefully this helps for now.
I would imagine this is because you are not setting hour minute and ampm before you query the database.
You probably need to requery the DB every cycle through the loop with the new hour, minute etc, however there is probably a more efficient way of doing this... i.e. Hit the db once for the whole days data, then use PHP to iterate out the info. 1 db call insted of 24*60*60
The below code is untested so please call me up on it if it doesn't work entirely but it should give you an idea:
$day = date('d');
$year = date('Y');
$month = date('m');
$start = mktime(0,0,0);
$thing_query="SELECT thing FROM things WHERE day='$day' AND month='$month' AND year='$year';
$result=mysql_query($thing_query);
while ($row=mysql_fetch_array($result)) {
// Loop through your hours mins etc and output desired values
}
}
All the data you need is stored in mysql_fetch_array($result) you can then loop through that where required. You dont want to be hitting the DB more than is necessary.
From what i can see you have the PHP to be able to do it - i think its a structure thing you are struggling with.
Your loop structure is wrong - you are consuming the entirety of the query result set on your first run around the parent for loop. And your internal while loop is simply setting $thing to the value of one field repeatedly, so $thing ends up being the LAST value returned from the query.
comment followup. An inefficient method of doing what you want would be:
$day = ...
$year = ...
$month = ...
$start = ...
for ($min = 0; ....) {
$hour = ...
$min = ...
$am = ...
$thing_query = "SELECT ...."
$result = mysql_query($thing_query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
printf(.... $row[0] ... );
}
}
But this would run a query for every single time point you're checking for. Why not just store the event's date/time in a single date/time field. YOu can reduce your query to
SELECT ... WHERE timestampfield BETWEEN startdatetime AND enddatetime
then use the results of that in PHP to build up your events. A single "larger" query would be more efficient than a long series of "small" ones.
You mixed up the order of your statements pretty badly. Here's the right way, and some additional comments:
$day = date('d');
$year = date('Y');
$month = date('m');
$start = mktime(0,0,0);
for($min = 0; $min < 24 * 60 * 60; $min += 30 * 60)
{
$hour=date("h", $start + $min);
$minute=date("i", $start + $min);
$am=date("A", $start + $min);
// you must set the string after $hour/$minute/$date have the right value
$thing_query="SELECT thing FROM things WHERE day='$day' AND month='$month' AND year='$year' AND hour='$hour' AND minute='$minute' AND ampm='$am'";
// query the database with the string
$result=mysql_query($thing_query);
// put things in an array
$things = array();
while ($row=mysql_fetch_array($result)) {
$things[] = $row[0];
}
// join the array so I have a comma separated list of things
$listOfThings = implode(", ", $things);
// ALWAYS use htmlspecialchars when sending data from the database to the browser!!!!
echo "<tr><td>" . date("g:i a", $start + $min) . "</td><td>" . htmlspecialchars($listOfThings) . "</td></tr>";
}

Categories