How would I go about timing between status changes in php? - php

When the status changes to prepare/preparing, the timer begins. I then want to stop the timer and calculate the difference when the status changes to ready, and store it as time in the database. Ive tried various ways but can't seem to get it working, what am I doing wrong? Thanks
if(isset($_POST['prepare'])){
$_SESSION['startTime'] = time();
$question2="UPDATE `order` SET orderStatus='Preparing', idEmployee='$_SESSION[id]' WHERE idorder='$_POST[id]'";
$sth = $db->prepare($question2);
$sth->execute();
}
if(isset($_POST['ready'])){
$total = time() - $_SESSION['startTime'];
echo date('h:i:s', $total);
$question2="UPDATE `order` SET orderStatus='Completed', timeCompleted='$total' WHERE idorder='$_POST[id]'";
$sth = $db->prepare($question2);
$sth->execute();
}
edit: I overcame the issues I was having by simply using a method within the DateTime class. I began by recording the time from when the order was taken, I also recorded the time of when the order was completed. I then used the method diff() to calculate the difference between the 2 recorded times and stored the results in my db.
if(isset($_POST['prepare'])){
$_SESSION['startTime'] = new DateTime();
$question2="UPDATE `order` SET orderStatus='Preparing', idEmployee='$_SESSION[id]' WHERE idorder='$_POST[prepare]'";
$sth = $db->prepare($question2);
$sth->execute();
}
if(isset($_POST['ready'])){
$endTime = new DateTime();
$i = $_SESSION['startTime']->diff($endTime);
$end = $i->format('%h:%i:%s');
$question2="UPDATE `order` SET orderStatus='Completed', timeCompleted='$end' WHERE idorder='$_POST[ready]'";
$sth = $db->prepare($question2);
$sth->execute();
}

Replace $total = time() - $_SESSION['startTime'] with $total = time() - strtotime($_SESSION['startTime'])
And add session_start(); to the top of your code if you didn't
Then it will work.

If both prepare and ready are actioned on the same machine by the same person (within the same session) - this code should work. If you believe all this to be true - I would check to make sure the session variables are being set print_r($_SESSION)
However, I would recommend when you update orderStatus to 'Preparing', creating a new column called timeStarted and update that to time(), then when you are updating to 'Completed' set timecompleted also to time()
You can then easily work out the difference, as currently (if this code did work timeCompleted is actually timeTaken) - for which you could even add a 3rd column which is the difference between the two for easy reporting.
Doing it this way means if it takes longer than the session or the computer restarts / re login the startTime is not lost

Related

Check if the time is more than 24h and show it

I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)

How to correctly manage a bidding system with PHP?

I've developed a bidding system with PHP and MySQL.
It works good in the most of the cases, but I've noticed there is a problem when offers are really close.
$now = DateTime::createFromFormat('U.u', microtime(true));
$dateMicroTime = date("Y-m-d H:i:s").".".$now->format("u");
$amountToRaise = 100;
$lastOffer = $bid->lastOffer();
//if there is an offer yet
if($lastOffer){
$newPrice = $lastOffer->getAmount()+$amountToRaise;
//else is the first offer
}else{
$newPrice = $amountToRaise;
}
//if the user is not the last bidder
if($user->getId() != $lastOffer->getUserId()){
$bidOffer = new BidOffer();
$bidOffer->setBidId($bid->getId());
$bidOffer->setUserId($user->getId());
$bidOffer->setAmount($newPrice);
$bidOffer->setTime($dateMicroTime);
$bidOffer->save();
//if this is not the first offer I give back the money to the previous user
if($lastOffer){
$lastUser = $lastOffer->user();
$lastUser->setCash($lastUser->getCash()+$lastOffer->getAmount());
$lastUser->save();
}
}
The code works well when offers are done in different moments, but users offer in the same seconds for example: 18:00:01.1299022 and 18:00.02.1222377
The user with previous offer doesn't receive back the offer.
How can I fix this? I've tried to use a temporary variable to block the statement temporary until every query are executed, but no success.
I would separate dateTime from microtime and would not use $dateMicroTime = date("Y-m-d H:i:s").".".$now->format("u");.
You can than use microtime to extract the last bidder. This can be done by adding a bid_utime column in your DB. If you are looking all the bidders for one auction chronologically ORDER BY table.bid_utime DESC.Last bidder can be found by ORDER BY table.bid_utime DESC LIMIT 1 as a return from $lastOffer = $bid->lastOffer();.
This also means you wont be saving your bids with: $bidOffer->setTime($dateMicroTime);but with something like:
$bidOffer->setDate($date); and $bidOffer->set_uTime($now);
But you can also skip all of this and return only the last entry from the bid table with SELECT * FROM bid_Table ORDER BY ID DESC LIMIT 1 and forget about dateMicroTime and microtime. Hope this helps.

PHP adding 2 variables not equaling to what its supposed to.(should be easy)

I have a column on my database called "hrs_worked" (int), where it stores the amount of hrs I've put into a project.
What i want to happen within my app is that:
A. i enter in my current worked hours,
B. Extract the hrs recorded on the database,
C. Take A and add it to B,
D. Take this new number and record the added total (A above and B)to the database since that will be my new total hrs worked on any given project.
i take in the new hours(that i submitted via form) with:
$hrs = mysqli_real_escape_string($c2d, $_POST['hrs']);
I pull out the old hrs in the database via:
$pullOutHrsQS = "SELECT hrs_worked FROM tlm_accounts WHERE company_name = '$compName'";
$pullOutHrsDoIt = mysqli_query($c2d, $pullOutHrsQS);
$originalHrsSet = (int)mysqli_fetch_array($pullOutHrsDoIt);
I then add them via:
$hrs += $originalHrsSet;
or
$hrs = $hrs + $originalHrsSet;
Now, lets say that my old hrs are 10hrs worked, and my new hrs are 5hrs worked, I want to add these together via
$hrs += $originalHrsSet;
or
$hrs = $hrs + $originalHrsSet;
and instead of this resulting in 15hrs, it results in 6hrs. The math is always wrong.
I guess the question i am asking is " What am i doing wrong?! Am i missing something?"
Thanks in advanced.
The better option would be to simply increment the field like this;
"UPDATE tlm_accounts SET hrs_worked = hrs_worked + '$hrs' WHERE company_name = '$compName'"
Hope that helps.
You don't need to SELECT data to UPDATE it (see Harry's answer), but for the record...
mysqli_fetch_array returns either an array or null but you are casting the return value to an int, so $originalHrsSet will always be either 1 or 0. Try this instead:
$result = mysqli_fetch_array($pullOutHrsDoIt);
$originalHrsSet = (int) $result[0];
You do not need to select a whole array for a single value. Try using mysqli_stmt_fetch instead. Try using var_dump with the values you enter just to make sure they're what you expect.

how to retrieve data on compare time in php

My code:
$query = "INSERT IGNORE INTO `user_app` (app_id,imei, package_name, sdk_name, sdk_version, app_version)
VALUES
('".$appid."','".$imei."', '".$pkg."', '".$sdkn."', '".$sdkv."', '".$appv."')";
$mysqli -> query($query);
$id = $mysqli -> insert_id ; //get last user insert id
$idt = date('G:i:s', time());
$new = strtotime($idt);
include('requestad.php');
When a new user registered, he'll get an ad from requestad.php in json format. Insert id is save in a separate variable named $id, if a user again hit via application (as application invoke after every 30min ) then he'll get again json ad. I am trying to do some stuff like user get ad only once in whole 24hours, this is possible with insert id and insert time stamp. I am doing something like that:
if ( $new == time() ) {
include('requestad.php');
} elseif ( $new < time() ) {
echo 'nothing';
}
But problem is i didn't save exact execution time in variable and save time is necessary for comparison. Also, i have to send some blank to user if he again request for resource. Pl have a look on this and help me to produce optimal solution.
Still i didn't apply any logic yet. I can achieve this through store time which is static and compare it to time() which shows real time. Still i am looking this one
$store_time=$row['time'];//pick up the store time of user
$store_time=strtotime($row['time']);//and convert it in strtotime.if alredy did no need to do this.
$new=strtotime("-24 hours",strtotime(time()));//substract the time to -24 hours.
if($new==$store_time)
{
//your code
}
else
{
//your code
}

comparing timestamps

HI, My php is very rusty and I can't quite remember how to do this.
I have a script that i only want to call every 15 minutes. I've created a table called last_updated. What I want to do is have some code at the top of my script that queries this last_updated table and if now() minus the last updated is greater than 15 minutes then run the script and also update last_updated to now...if it isn't don't run the script. Does this make sense?
Now I know when I'm updating last_updated I need to use now() To put a new timestamp in but I;m not sure how to do the comparing of now with the db value to see if it's greater then 15 mins.
Any ideas
<?php
$pdo = new PDO('mysql:host=your_host;dbname=your_database', $user, $password, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
// query the database. change
$stmt = $pdo->query('SELECT UNIX_TIMESTAMP(last_updated_date) FROM last_updated ORDER BY last_updated_date DESC LIMIT 1');
$lastUpdatedTimestamp = $stmt->fetch(PDO::FETCH_COLUMN);
if ((time() - $lastUpdatedTimestamp) > (60 * 15)) {
touch($file);
// do stuff
}
time() gives you the current time in seconds. You should probably unroll 60 * 15 to 900, I just provided it with both numbers to illustrate what was going on.
Also, a file might be better for this than a database table. Have a look at the touch()
function. It changes the modification time of a file, or creates an empty file with the current time as the mod time if it doesn't exist. You can check the file mod time with filemtime()
<?php
$lastUpdated = null;
$file = '/path/to/writable/file/with/nothing/in/it';
if (file_exists($file)) {
$lastUpdated = filemtime($lastUpdated);
}
if (!$lastUpdated || (time() - $lastUpdated) > 900) {
touch($file);
// do stuff
}
You seem to use MySQL as the DBMS. In that case and if you want you can let MySQL do most of the work:
SELECT
pit < Now()-Interval 15 Minute as mustUpdate
FROM
last_updated
WHERE
siteId=?
pit is your DateTime field and siteId is some condition you may have if you store more than one record in the table (which sounds like a good idea to me).
The result (if there is such a record with siteId=?) contains a field mustUpdate which either contains 0 or 1, 1 indicating that the value of pit is more than 15 minutes in the past.

Categories