I have searched and all questions are related to the comparison being in the query.
I'm building an e-commerce website and I have a feature that allows the customer to return products 7 days upon date of purchase.
So I have, a column in mysql that tells when they bought. And I have to compare the current time (Philippines) to the mysql column, so the system can tell if they will have the option allowed.
The logic I'm thinking of but can't find the right syntax:
(inside the while loop that fetches columns as arrays, my variable is $info)
$php_current_datetime = date_now_in_php_format;
$purchase_datetime = $info['purchase_date'];
$expire_date = $info['purchase_date'] + 168 hours;
Then compare it
if($php_current_datetime < $expire_date){
echo "show the option";
}
else{
echo "already expired";
}
I would recommend making all the values timestamps and calculate the difference between them in seconds.
$secDifference = 60*60*168;
$dtObject= new DateTime($mysqlDatetime);
if ($dtObject->getTimestamp() > time()-$secDifference) {
//show the option
}
Related
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.
I'm writing a time logging programme for a client who is a piano tuner, and I've written the following PHP code to give a record a status of 'to do':
$last_tuned = '2017-01-05';
$tuning_period = 3;
$month_last_tuned = date('Y-m', strtotime(date('Y-m-d', strtotime($last_tuned))));
$next_tuning = date('Y-m', strtotime($month_last_tuned.(' +'.$tuning_period.' months')));
if (time() > strtotime($next_tuning.' -1 months')) {
if (time() > strtotime($next_tuning)) {
return 'late';
} else {
return 'upcoming';
}
}
As you can see, the $last_tuned variable is of the date(YYYY-MM-DD) format. This is then converted to a (YYYY-MM) format.
Once convered, an additional number of months, identical to $tuning_period is then added to the $month_last_tuned variable giving us a month and year value for when we need to add a new record.
If the current time (found with time()) is greater than the $next_tuning variable - 1 month, it returns that the task is upcoming. If it's after the $next_tuning variable, it returns that the task is late.
I now have to write a MySQL query to list the items that would return as upcoming or late.
How would I write this in MySQL? I'm not very good with MySQL functions, and some help would be much appreciated.
My attempt at the logic is:
SELECT * FROM records
// The next lines are to get the most recent month_last_tuned value and add the tuning_period variable
WHERE
NOW() > (SELECT tuning_date FROM tunings ORDER BY tuning_date ASC LIMIT 1)
+
(SELECT tuning_period FROM records WHERE records.id = INITIAL CUSTOMER ID)
I know that that is completely wrong. The logic is pretty much there though.
My database schema is as follows:
I expect the rows returned from the query to be on-par with the 'late' or 'upcoming' values in the PHP Code above. This means that the rows returned will be within 1 months of their next tuning date (calculated from last tuning plus tuning period).
Thanks!
You'd probably be better off with using the DateTime object instead of manipulating date strings.
$last_tuned = '2017-01-05';
$tuning_period = 3; // months
$dt_last_tuned = DateTimeImmutable::createFromFormat('Y-m-d',$last_tuned);
$dt_next_tuning = $dt_last_tuned->add(new DateInterval('P3M'));
$dt_now = new DateTimeImmutable();
$dt_tuning_upcoming = $dt_next_tuning->sub(new DateInterval('P1M'));
if( $dt_now > $dt_next_tuning) {
return 'late';
}
if( $dt_now > $dt_tuning_upcoming) {
return 'upcoming';
}
You can also use these DateTime objects in your MySQL queries, by building the query and passing through something like $dt_next_tuning->format('Y-m-d H:i:s'); as needed.
Given your table structure, however, it may be easier to just get all the relevant records and process them. It's a little difficult to tell exactly how the pieces fit together, but generally speaking MySQL shouldn't be used for "processing" stuff.
I am making a meeting room booking system in which there should be no times within the start and end dates so in theory the validation should check for no dates/times within one start and end date time frame.
I have two tables, I can insert into it fine with both start and end dates so the only columns i am interested in at the moment are these
meetingrooms
|------------------------------------||- bookingtime -|-bookingend-|
I understand the principle behind the sanity check and the check i can do in psudocode. Here is the code i have got so far -
>
p4a_db::singleton()->query("INSERT INTO meetingrooms(location_id, bookingtime, bookingend, merono_id)
WHERE bookingtime < " . $date . " AND bookingend > " . $date . "
OR
bookingdate < " . $date . " AND bookingend > " . $dateend . "
VALUES(?,?,?,?)",
array($location, $date, $dateend, $merono));
I don't want to insert data directly into the statement but until i understand how to do this i am stuck, so the question,
How do i perform a sanity check before the data is inserted so that i don't get dates within booked times.
any help would be greatly appreciated.
Edit:
I've been overthinking my answer and I realized that the old solution will not work in your case since you need the time span, comparing the start and end date is useless.
My way of processing this would be:
Save the dates as int, use 24h system (7:40am is 740, 9:50pm is 2150)
Check for stored dates where: (Start<NewStart<End)
Check for stored dates where: (Start<NewEnd<End)
When processing several rooms, just store room number + time as int. That way you can still use the method from 2 and 3.
2 and 3 can be done in a sql query, check out this link.
Old answer (checking for duplicates)
This is an example of how to check for duplicates (in this case email) before inserting the text:
$emailexist = $mysqli->prepare("select email from users where email = ?");
$emailexist->bind_param('s', $email);
$emailexist->execute();
$emailexist->store_result();
if ($emailexist->num_rows > 0) {
$emailexist->close();
$mysqli->close();
return true;
}
else {
$emailexist->close();
$mysqli->close();
return false;
}
It checks if there are rows which contain the string. If so (if number of rows higher than 0) it returns true (which means, the date already exists).
You can just adapt this to you code.
However, you could also just set the columns to UNIQUE. Then you get an error when trying to insert it. It is easier and you won't have problems with concurrent connections.
after a long and intensive search, I have now got a working example of this method, along with a method of protecting against sql injection, here's the code;
if ($this->BookingValue == 1)
{
$sql = "SELECT COUNT(*) as num FROM meeting_room_bookings
WHERE
(
(? < start_at AND ? > start_at)
OR
(? > start_at AND ? < end_at)
)
AND
meeting_room_id = ?";
$result = p4a_db::singleton()->fetchRow($sql, array($date, $date, $date, $dateend, $merono));
if ( 0 == $result["num"] )
{
p4a_db::singleton()->query("INSERT INTO meeting_room_bookings (start_at, end_at, meeting_room_id)
VALUES
(?,?,?)", array($date, $dateend, $merono));
return true;
}
else
{
return false;
There isn't much to explain about this code, but in term of differences, (excluding the change in column names with the table) the query is now prepared before the value is set, then it is possible to use it in an if statement, thus allowing the validation to take place to filter results between different dates.
along with this i have added validation to stop dates from other meeting rooms being included within the statement via the AND statement where the meeting room id is limeted to a single value.
Although now, which will lead on to a separate question is another thrown error that comes from this statement, i know the insert is sound but something from this prepared statement causes the error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
File: Pdo.php, Line: 234
Although now i am looking into a error that is thrown from the prepared statement and will update this answer when there is a fix, thanks for the help.
I have different events wherein users can sign-up. These events have their own date and time schedules. How do I add a sort of a time restriction wherein it will automatically restrict the users from signing up?
For Example, I have an event scheduled on March 10, 2012. Users will only be allowed to sign-up for the event up to March 9, 2012.
My table for the events contains the following fields:
eventID/eventName/eventTime/eventDate/eventCapacity/eventDescription
Thanks for your help!
Get event using eventTime/eventDate parameter and check today's date is smaller or not using datediff function.if date is bigger then reuse to accept.
Retrieve the event date and the current date and calculate the difference using PHP date object
mysql_connect("localhost", "root", "");
mysql_select_db("myDb")
$query="SELECT * FROM events WHERE eventName='$eventName' ";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$currentTime= new DateTime("now UTC");
$eventTime=new DateTime($row['thisEventDate']);
$interval=$eventTime->diff($currentTime);
$days=$interval->format('%d');
if($days<=1) {
print "sorry too late, we're sold out";
}
else {
//allow for registration fields.
}
By comparing the current date and desired date or taking the difference or current date and desired date, and accordingly displaying the HTML form into the PHP if loop
Sample
if($days<=1) {
echo "where were you wen i asked you to do so!!! ";
}
else {
<form>
field1
field2
...
</form>
}
here, $days is difference of dates
I am creating an online calendar for a client using PHP/MySQL.
I initiated a <table> and <tr>, and after that have a while loop that creates a new <td> for each day, up to the max number of days in the month.
The line after the <td>, PHP searches a MySQL database for any events that occur on that day by comparing the value of $i (the counter) to the value of the formatted Unix timestamp within that row of the database. In order to increment the internal row counter ONLY when a match is made, I have made another while loop that fetches a new array for the result. It is significantly slowing down loading time.
Here's the code, shortened so you don't have to read the unnecessary stuff:
$qry = "SELECT * FROM events WHERE author=\"$author\"";
$result = mysql_query($qry) or die(mysql_error());
$row = mysql_fetch_array($result);
for ($i = 1; $i <= $max_days; $i++) {
echo "<td class=\"day\">";
$rowunixdate_number = date("j", $row['unixdate']);
if ($rowunixdate_number == $i) {
while ($rowunixdate_number == $i) {
$rowtitle = $row['title'];
echo $rowtitle;
$row = mysql_fetch_array($result);
$rowunixdate_number = date("j", $row['unixdate']);
}
}
echo "</td>";
if (newWeek($day_count)) {
echo "</tr><tr>";
}
$day_count++;
}
The slowness is most likely because you're doing 31 queries, instead of 1 query before you build the HTML table, as Nael El Shawwa pointed out -- if you're trying to get all the upcoming events for a given author for the month, you should select that in a single SQL query, and then iterate over the result set to actually generate the table. E.g.
$sql = "SELECT * FROM events WHERE author = '$author' ORDER BY xdate ASC";
$rsEvents = mysql_query($sql);
echo("<table><tr>");
while ($Event = mysql_fetch_array($rsEvents)) {
echo("<td>[event info in $Event goes here]</td>");
}
echo("</tr></table>");
Furthermore, it's usually a bad idea to intermix SQL queries and HTML generation. Your external data should be gathered in one place, the output data generated in another. My example cuts it close, by having the SQL immediately before the HTML generation, but that's still better than having an HTML block contain SQL queries right in the middle of it.
Have you run that query in a MySQL tool to see how long it takes?
Do you have an index on the author column?
There's nothing wrong with your PHP. I suspect the query is the problem and no index is the cause.
aside from their comments above, also try to optimize your sql query since this is one of the most common source of performance issues.
let say you have a news article table with Title, Date, Blurb, Content fields and you only need to fetch the title and display them as a list on the html page,
to do a "SELECT * FROM TABLE"
means that you are requiring the db server to fetch all the field data when doing the loop (including the Blurb and Content which you are not going to use).
if you optimize that to something like:
"SELECT Title, Date FROM TABLE" would fetch only the necessary data and would be more efficient in terms of server utilization.
i hope this helps you.
Is 'author' an id? or a string? Either way an index would help you.
The query is not slow, its the for loop thats causing the problem. Its not complete; missing the $i loop condition and increment. Or is this a typo?
Why don't you just order the query by the date?
SELECT * FROM events WHERE author=? ORDER BY unixdate ASC
and have a variable to store the current date you are on to have any logic required to group events by date in your table ex. giving all event rows with the same date the same color.
Assuming the date is a unix timestamp that does not account for the event's time then you can do this:
$currentDate = 0;
while(mysql_fetch_array($result)){
if($currentDate == $row['unixdate']){
//code to present an event that is on the same day as the previous event
}else{
//code to present an even on a date that is past the previous event
//you are sorting events by date in the query
}
//update currentDate for next iteration
$currentDate = $row['unixdate'];
}
if unixdate includes the event time, then you need to add some logic to just extract the unix date timestmap excluding the hours and minutes.
Hope that helps