PHP mysqli Recent activity by date - php

I've tried a bunch of different ways to do this that other people have done but I can't quite get it. I have a database with a bunch of print job orders, and I have a print order TRACKER on my website. On the tracker page, I'd like to display the recent activity done by displaying all of the print jobs created in the last month.
I'm trying to do this without over complicating it also.
Here I just try to make an SQL query saying WHERE Date_Completed BETWEEN lastMonth && today. Here's one of the latest snippets that I've tried (not all of the code):
$date = new DateTime('now');
$today = $date->format('Y-m-d H:i:s');
$lastMonth = date_modify($date, "-1 month");
$result = $lastMonth->format('Y-m-d H:i:s');
SELECT * FROM other_card WHERE Date_Completed BETWEEN '$today' AND '$result' order by Date_Completed");
Any information is helpful! I know the variables are named a bit odd. Just been trying to get it to work.

Try structuring the query instead like:
SELECT * FROM other_card WHERE Date_Completed < '$today' AND Date_Completed > '$result' order by Date_Completed");

You don't need to generate the dates in PHP. MySQL can do it for you:
SELECT ...
WHERE ... Date_Completed BETWEEN now() - interval 1 month AND now()
This also takes care of some edge cases where PHP could be generating the dates at 11:59:59pm on the last day of a month, and the query doesn't actually executed until 00:00:01am next month.

Between works from smaller to bigger value, not opposite
You don't need between at all, just Date_Completed > some date will do.
On a side note, you should be using prepared statements, instead of adding value directly to query

Related

Database living in the past?

I have events in my MySQL database wich all have a date. When I perform a SQL query to get all the events in the future, I get an error... Although, the date of the events are in the future. When I change my SQL request to select dates in the past, I get those from the future...
The SQL statement below has worked before, but for some reason it stopped working...
I use this SQL request:
$sql = "SELECT * FROM calendar WHERE date >= CURDATE() order by `date`";
I get an empty array as result...
However if I change the query to this, I get all the events in my database:
$sql = "SELECT * FROM calendar WHERE date <= CURDATE() order by `date`";
This is my database data. In my opinion, all data are in the future...
The format of the date table is a default date-type:
When I ask my server about the time echo date("Y-m-d"); I get todays date as result...
So where do I make a mistake?
You may be checking the wrong date field. Do you have a created date as well as a scheduled date?
I could be crazy from the cold medicine I am on at the moment, but your date table can't possibly be the date of your calendar items, the id filed is only an int(2), that seems kind of small.
maybe something simplier? I notice the column name in your table is date, which also is the name of a function date() that returns the date part of a datetime value. If thats the case
$sql = "SELECT * FROM calendar c WHERE c.`date` <= CURDATE() order by `date`";
would do the trick. Even if not mysql itself, the gui app youre using (seems like phpmyadmin to me) might get confused.
(btw, you forgot the closing tick of date in the order by clause)
getting an empty set is meaning nothing is found matching. I would look at your formatting of your date. The only other thing i was thinking is that it is comparing an unmatched type so just returns an empty set.
use DATEDIFF :
DATEDIFF
WHERE DATEDIFF(date, CURDATE) > 0
Before you make your query, run this one:
SET time_zone = '-2:00'; // or whatever your time zone is.
Don't ask me how or why, but I've truncated my table and re-inserted some data and my query seems to work just fine:
$sql = "SELECT * FROM `calendar` WHERE `date` >= CURDATE() order by `date`";
So, despite the fact the problems seems to be solved by truncating my table, I would like to know the answer to the why-question... Anyone can provide me with it?

Search date in database PHP

When I was a start up student in PHP I made my database to store dates the date and time together, now I have a big problem, I have already in the database over 3000 orders but when I want to make a search with dates am I in big trouble because the dates and time is together in one field, I tried to make the query like where date LIKE '%$date' but I'm getting no results, has anybody any idea what I can do now?
And also how can I change the whole database it should be all dates and time separately and it should not effect my database?
UPDATE:
The data in the database looks like, 10/16/2012 5:00pm
Appreciate any help.
Why %$date? You should do the opposite.
WHERE date LIKE "".$date."%"
In response to the sections of your question:
1. Finding the dates you need in the current schema.
Based on your edits, use:
<?php
$query = "SELECT * FROM table_name WHERE `date` LIKE '{$date}%'";
?>
A query similar to what you posted should help you:
<?php
$query = "SELECT * FROM table_name WHERE `date` LIKE '%{$date}%'";
?>
Please note that your use of % in your question ( '%$date' ) will only match values that end with $date, while the pattern in my example ( '%{$date}%' ) will match values that have $date anywhere in them. Alternatively, you could use '{$date}%' to match date at the beginning of the value -- not sure which you want.
2. Updating your schema to split date and time into two columns.
The first step you should take here, is to add two columns ( date_only and time_only ) to your table. Next, update your code to process and store this information in addition to the 'all-in-one' date column your are currently using; you don't want to break your current codebase by switching over in one step. Once you can verify that date/time data is being written the way you want it to be, the third step is to read (and log) from the new date/time columns along with your production reads to date. Once you can verify that the reads are working as planned, switch over your dev environment to read from the new columns and test until you are confident that everything works.
You can do the following:
$date = "2012-03-08";
$sql = "SELECT * FROM table WHERE date => '$date 00:00:00' AND date =< '$date 23:59:59'
Edit: Seeing your edit, this does not work anymore. You will need to convert your date column to a proper MySQL datetime or TIMESTAMP type.
At the current database design you could use something like this:
date
$date = "10/16/2012";
$sql = "SELECT * FROM table WHERE date LIKE '$date%'
time
$time = "5:00pm";
$sql = "SELECT * FROM table WHERE date LIKE '%$time'
If it's a DATETIME field, you can use
WHERE DATE(datetime_field) = '01-01-2012';
or (better, as it can use indexes)
WHERE datetime_field >= '01-01-2012 00:00:00' AND datetime_field <= '01-01-2012 23:59:59';
this is what worked for me
$date = "2018-05-13";
"SELECT * FROM $username WHERE reg_date LIKE '%$date%'";

Select Before The Date

I have a date, say its called $date. I want a a mysql_query to search a select number of weeks,days or even months before my $date. Is this possible? My explanation is not the greatest, but I do need a answer for this and do not know how to properly question it.
You could use mysql interval function?
"select * from table where `date` BETWEEN DATE_SUB(".$date.",INTERVAL 15 DAY ) AND CURDATE( )
That'll return the records from the last 15 days, you could use = insted of between if you want the records exactly 15 days old, or modify it for days, months, etc.
edit: if your working with php's time() remeber to use FROM_UNIXTIME($phpdate) inside your query.
i have a solution for this in SQL, Take it, if it would helps you
Day($date) gives you the date in the vaariable
Month($date) gives you the Month in the vaariable
Year($date) gives you the year in the vaariable
using simple where conditions, now you can search for a particulars
You can use the DATE_ADD and DATE_SUB functions to modify a date, and mysql understands a BETWEEN clause using dates. However, you can also use the TIMESTAMPDIFF function like so:
"SELECT foo FROM table WHERE TIMESTAMPDIFF(DAY, dateField, '$date') < '$desired_days'"

Monthly categories with MySQL DATE Type

I'm building a mini news CMS where the news added are sorted using a DATE type column e.g. INSERT date_posted=NOW(), etc.
I can then easily list out all the available months with: SELECT DATE_FORMAT(date_posted, '%M %Y') as date_posted. This makes the monthly categories list.
The issue I'm having is with displaying all the news by a particular month. I have tried to pass the date_posted variable in the URL but have failed to actually incorporate it in my Query. If for instance, I try WHERE date_posted=\"2009-10-16\", the result is all the news of that day. WHERE date_posted=\"2009-10\" doesn't work on the other hand.
I've passed this parameter in the URL DATE_FORMAT(date_posted, '%M%Y') as month which echos out October2009 for example. Then WHERE date_posted=$month returns nothing because firstly I'm guessing it's in the wrong format, secondly, the MySQL data type does not output what I want as evidenced by the aforementioned hard-coded example.
Please help,
Thanks!
You should use a range in your where clause:
where date_posted >= cast('2009-10-01' as date)
and date_posted < cast('2009-11-01' as date)
To get the "2009-10-01" and "2009-11-01" dates, you can use PHP's strtotime and date functions:
$date_from_querystring = "2009-10";
$start_date = $date_from_querystring . "-01";
$end_date = date("Y-m-d", strtotime($start_date . " +1 month"));
You could also use the year and month functions, but then you won't get any benefit from any indexes you might be able to use, so it's generally not as good a solution as the range. An example:
where year(date_posted) = 2009 and month(date_posted) = 10

Trying to filter a mysql table by date using a single query

I'm trying to request any records from a table that appear on or after today's date, using a single query.
All the dates for each record are stored in separate columns e.g.. - one for month, one for year, and one for day.
obviously i've been getting all records that occur after the year in today's date
$sql = "SELECT * FROM table WHERE year>=".$year_today."
ORDER BY year, month, day";
Then i've been trying to filter that down a bit, by using:
$sql = "SELECT * FROM table
WHERE year>=".$year_today." && month>=".$month_today."
&& day>=".$day_today."
ORDER BY year, month, day";
And in order to test it, i created a record in the database with yesterdays date, yet, this record still appears in the list of returned records. What am i doing wrong? :(
This can be achieved using time functions in a nice way, while it's better when using a DATE column.
SELECT * FROM TABLE WHERE TIMESTAMP(CONCAT(year,"-",month,"-",day)) >= CURDATE()
ok, that's evil as it doesn't use an index ... proper thing would be a DATE column, but doing all this by hand is annoying asyou also have to consider the case where year is bigger but months is smaller and stuff ....
I don't know if you can use "&&" instead of "AND" in your context - maybe try changing your SQL to use
" AND month>=".$month_today." AND day>=".$day_today."
EDIT :
as an extension to Nick's answer, to make the sql behave correctly you could code :
$sql = "SELECT * FROM table WHERE (
(year>".$year_today.")
OR (year=".$year_today." && month>".$month_today." )
OR (year=".$year_today." && month=".$month_today."&& day>=".$day_today.")
)
ORDER BY year, month, day";
...but this starts to get a whole lot messier than converting to dates and using date comparison
EDIT2:
but then again, if these columns are indexed, the indexes might be used. It's still a lot more effort to code SQL this way if performance using conversion to dates is totally acceptable.
To compare dates with dates:
SELECT * FROM table WHERE
STR_TO_DATE(
CONCAT(year
, '-'
, right(concat('00', month), 2)
, '-'
, right(concat('00', day), 2))
, '%Y-%m-%d')
>= STR_TO_DATE('2009-12-11', '%Y-%m-%d')
to check if a date is after another date this query will fail:
$sql = "SELECT * FROM table WHERE year>=".$year_today." && month>=".$month_today." && day>=".$day_today." ORDER BY year, month, day";
day 12 march of februari is smaller then day 15 in februari, but is still after it, because it's in a different month....

Categories