im trying to retrieve a set of id's that are due to expire within the next 7 days, and for the life of me cant get my query to work
$target_date = date('Y-m-d', strtotime('+7 days'));
$sql = "SELECT subscriptions.`id` FROM subscriptions WHERE date($target_date) <= expires AND cust_id =$_SESSION[uid]";
any help would be greatly appreciated
This is fine:
$target_date = date('Y-m-d', strtotime('+7 days'));
As it structures the date in the same way as MySQL [YYYY-MM-DD]
I've switched your query around and applied the DATE() function to the 'expires' field and not your $target_date as it doesn't need to. Your expires field might be in [YYYY-MM-DD HH:MM:SS] format, which might be why it's not working:
$sql = "
SELECT subscriptions.id
FROM subscriptions
WHERE DATE(expires) >= '$target_date'
AND cust_id = '$_SESSION[uid]'";
Echo out the $sql query to find out if its executing it properly and Use the or die(mysql_error()); to tell you where it's failing.
Use SQL escaping too (Either PDO or mysqli) as has been outlined in another answer.
Hope this helps.
If you create a date in a roughly MySQL compatible format, it should work without having to use the DATE function, just compare it as if it were a string.
Your code is in dire need of some proper SQL escaping that would fix this problem and likely a worryingly large number of others in your application.
The query running in PDO or mysqli would look roughly like:
$target_date = date('Y-m-d', strtotime('+7 days'));
$sql = "SELECT subscriptions.`id` FROM subscriptions WHERE ?<=expires AND cust_id=?";
You can then call the appropriate bind_param method to link in the right values to those placeholders.
You can do it with MySQL:
SELECT subscriptions.`id` FROM subscriptions WHERE date_add(curdate(),interval 7 day) <= expires AND cust_id =$_SESSION[uid]
Related
I have the following at the top of every page so when the website is loaded by anyone PHP deletes any record in a specific database table that is older than 3 days.
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < DATE_SUB(DATE('m-d-Y'), INTERVAL 3 DAY");
The problem is nothing is being deleted.
The data type for my date column is varchar(20) and when I insert a date into MySQL it is entered using date("m-d-Y"). The name of my date field is date. So it appears that the above query would be correct, but I have done something wrong, and I am not certain as to what since every example I've looked at has basically looked the same except they used now() instead of date() but I use a specific date format so I can't use now() in my query.
What have I done wrong?
I even tried putting it into a function:
function deleteOversizeRows() {
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < DATE_SUB(DATE('m-d-Y'), INTERVAL 3 DAY");
}
deleteOversizeRows();
Try to provide date by calculating first and then use it in query like below
$date = date("m-d-Y", strtotime('-3 day'));
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < '".$date."');
It might help you. If need any other solution or help, do ask here.
Use MySQL function TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2);
Function calculates difference between two dates and returns output based on the unit parameter passed .
Try this:
DELETE FROM postedLoads WHERE TIMESTAMPDIFF('DAY',date,now())<3;
For detailed info of function:http://www.w3resource.com/mysql/date-and-time-functions/mysql-timestampdiff-function.php
Basically i'm doing a simple wedding planner and i am trying to check whether the date that the user has inserted as available or whether the venue is booked. Basically, it's falling over with my SQL query. Initially i am setting the time:
$time = mktime(0, 0, 0, $month, $day, $year);
Then i have an sql query where i am checking it against an id variable that is previously set and the date that is passed through.
$sql2 = "SELECT * FROM venue_booking WHERE date_booked = ".$time." AND venue_id =".$id;
In this case the date in the database is 2015-01-01 and the date i'm passing through is 2015-01-01, I am checking this in an if statement if the amount of rows returned from the database is greater than 0 then echo booked, else echo available.
Even if the output is meant to say booked it still says available. Is there an issue with the way i am checking the time against mysql's date.
date_booked - This is a MySQL date (2014-01-01)
Anybody have any ideas?
Your current query is missing quotes around your date string so it wouldn't work as it is.
But to answer your question, just pass a valid date string in YYYY-MM-DD format and your query would work:
$date = $_POST['date'];
// Put date validation code here. I.e. make sure it is in YYYY-MM-DD
// format, etc. Might as well escape it, too since you aren't using
// prepared statements.
$sql2 = "SELECT * FROM venue_booking WHERE date_booked = '".$date."' AND venue_id =".$id;
I should also mention that you should probably switch to using prepared statements as it will make using user-provided data in queries safer.
Here is a possibly useful example of date validation. If you need to convert the date from one format to another, this will show you how.
mktime() returns a PHP timestamp, which is a unix timestamp, which is "seconds since the epoch", aka Jan 1/1970. You cannot directly compare that against a mysql date field. You'd literally be doing
WHERE '2014-01-01' = 12345678
Try
$ts = date('Y-m-d h:i:s', mktime(0,0,0,$month, $day, $year));
$sql = "SELECT ... date_booked = '$ts'";
MySQL table "flightSched" is connected to time, similar to the one below:
flightNo |day |time |arrivalTimeSec
=============================================
WERE112 |Tuesday | 1:00 |1381186800
FGHG234 |Tuesday |23:00 |1381266000
CGHF345 |Tuesday |00:00 |1381183200
I have a mysql query that select all data between two times. This is the query:
$CurrentTimeMinus30min = date('H:i', strtotime('-30 minutes')); //Current Time minus 30minutes
$CurrentTimeMinus30min = strtotime($CurrentTimeMinus30min);
$CurrentTimePlus4Hours = date('H:i', strtotime('+240 minutes')); //Current Time plus 4 hours
$CurrentTimePlus4Hours = strtotime($CurrentTimePlus4Hours);
$query = $mysqli->query("
SELECT * FROM flightSched
WHERE day = '$currentDay'
AND arrivalTimeSec
BETWEEN '$CurrentTimeMinus30min'
AND '$CurrentTimePlus4Hours'
");
I was advised to used strtotime() function on the time values to be able to use them in a BETWEEN MySQL query. This doesn't seem to be working at all.
Where am I going wrong with this query? Any help will be appreciated.
today I found the same problem with yours (mine about coordinates).
and I found out that in some case, a BETWEEN operator can only be used like this
..... WHERE columname BETWEEN smallervalue AND biggervalue
previously I've tried with the biggervalue at front since I dealt with negative numbers, and it fails.
you might found the same problem with your timestamp.
strtotime returns a timestamp so passing that into the MySQL query, like above, won't work. Try using FROM_UNIXTIME instead.
$query = $mysqli->query("SELECT * FROM flightSched
WHERE day = '$currentDay'
AND FROM_UNIXTIME(arrivalTimeSec) BETWEEN FROM_UNIXTIME($CurrentTimeMinus30min) AND FROM_UNIXTIME($CurrentTimePlus4Hours) " );
EDIT - I hadn't noticed that arrivalTimeSec was also a timestamp. The above mightn't be a workable answer for you, but try it. If it doesn't work, as others say, define what you mean by
This doesn't seem to be working at all.
Is it not returning any rows? Is it returning an error? Can you print out $CurrentTimeMinus30min and $CurrentTimePlus4Hours? Narrow down the potential areas for problems.
Have you tried to encapsulate the between? This could potentially solve your problem:
SELECT * FROM flightSched
WHERE day = '$currentDay'
AND (arrivalTimeSec BETWEEN '$CurrentTimeMinus30min' AND '$CurrentTimePlus4Hours')
Also why not just do:
$CurrentTimeMinus30min = strtotime('-30 minutes');
Or
$CurrentTimeMinus30min = strtotime(date('Y-m-d H:i:00', strtotime('-30 minutes')));
Please send us some examples of what your variables are generating.
Your time calculation with date("H:i",...) and strtotime(..) seems to actually produce the correct results, although there is a much easier way to add/substract n minutes from the current time:
$now = time();
$currentTimeMinus30min = $now - 30*60; // 30 minutes * 60 seconds
$currentTimePlus4Hours = $now + 4*60*60; // 4 hours * 60 minutes * 60 seconds
(I assume your time entries in your database are unix timestamps.)
Your query looks fine, too, but there are a few things to keep in mind:
You have redundant fields in your database (day and time can be calculated from the timestamp)
Working with time variables can easily lead to confusion, as the time passes on and if you have no entries in your database that match the specified time range (-30m to +240m) the result set is empty. So to test the query update the database with current time stamps.
I would suggest the following:
Drop the redundant columns day and time and just use the timestamp as base for your calculations, because the day and time is already included in the timestamp. So just use a simple query like
select * from flightShed
where arrivalTime between $begin and $end
all - fairly simple query question that's been hounding me: How do I query for entries with a date and time only greater than now, or when the query is run (page requested)?
I've seen some examples but they aren't good enough for me to modify. Here's my code:
$todaysDate = date("Y-m-d h:i:s");
$params = array('select'=>'*', 'limit'=>3, 'orderby'=>'t.event_StartDate ASC', 't.event_StartDate < "$todaysDate"' );
An example of the variable "t.event_StartDate" outputs "2010-12-10 22:18:42" so I assume that may be how it's saved in the database.
I suspect I'm not building the date correctly or I need to be using a time function I'm not familiar with in MySQL. Help? This is for outputting a series of events with date and time.
I think you reverse the use <, it should be >
try
SELECT ... WHERE t.event_StartDate>NOW();
/* you don't even need to set $todaysDate */
t.event_StartDate > NOW() don't will returns nothing? a date higher of now lol. I'm confused.
I want to allow my users to search the database for a row that was submitted on a certain day. The date is entered into the field in the database using the date() function which is great, but when i use the php strtotime function, of course the dates are not exactly the same.
Is there some clever mysql function that can help me with this?
I had an issue with this before.
You're best to generate a start and end date then use the BETWEEN function instead.
So something like this:
$start_date = "2009-01-01 00:00:00";
$end_date = "2009-01-01 23:59:59";
$sql = "SELECT * FROM table WHERE date BETWEEN '$start_date' AND '$end_date' AND id = 'x';
Of course you would just pull your dates from the DB using strtotime and append the time stamps - depends how you used date()
Hope this helps :)
You can use MySQL's DATE() function to extract date part of the timestamp:
select ... from table ... where DATE(date_column) = '2010-01-25';
If you have problem submitting '2010-01-25' from PHP, you can use PHP's date function with 'Y-m-d' as parameter to only get the date part.
$d = date('Y-m-d', strtotime(...));
Looking at your question closely, it seems you'll need both of those. First use PHP's date function to get only the date part and then use MySQL's date to match only those records.
PHP:
$timestamp_from_php = strtotime('December 25, 2009');
SQL:
select
`fields`
from
Table t
where
date_format('Y-m-d', t.`datetime_field`) = date_format('Y-m-d', '$timestamp_from_php')