Using Date functions to pull records from database - php

I'm truly stumped on something - I have a table in my database with a column called 'today' that has Date and Time records. The column has entries that look like this:
October 25, 2014, 4:58 am
October 25, 2014, 4:36 am
I'm having trouble pulling the rows by date; I think the time stamp is messing with the MySQL query. And I need an SQL query to pull any records where the variable $today matches the date information in the column 'today'. This doesn't work:
$today = date("F j, Y"); // looks like this: October 25, 2014
$result = mysqli_query($link,"SELECT * FROM records WHERE today = $today"); // 'today' represents the column in the table
while($row = mysqli_fetch_array($result)) {
echo var_dump($row);
}
I just get an empty result, I think due to the time stamp. Can someone advise on a better MySQL query that will only grab the rows where $today matches the date in the 'today' column?

Although storing the date and time as string in varchar is not really a good idea, you could still alter your query to match string containing the current date with a LIKE statement:
$result = mysqli_query($link,"SELECT * FROM records WHERE today LIKE '$today%'");
That is just to get your current setup working as a temporary fix but i highly suggest you take a look at datetime and timestamp or similar date types if this is a serious project and not just playing around. with programming.
UPDATE
With a datetime you could get the dates which are the same as today with:
SELECT * FROM `records` WHERE `today` = CURDATE();
with a timestamp you would need to pass it as date so your query would be:
SELECT * FROM `records` WHERE date(`today`) = CURDATE();

You can just use the MySQL date functions:
SELECT *
FROM records
WHERE today = CURRENT_DATE;
If there is a time component on the today column, then the best structure is:
SELECT *
FROM records
WHERE today >= CURRENT_DATE and today < date_add(CURRENT_DATE, interval 1 day)

It's obvious that both dates are not equal. Both dates are treated like text values and are not equal. You need to convert the column containing date in your MySQL query as such:
$result = mysqli_query($link,"SELECT * FROM records WHERE DATE_FORMAT(today, '%F %j, %Y') = $today");
Note that you have to change your column to store values of the type of DATE. Or just use queries as proposed in other answers.

Related

Select mysql date range based on a VARCHAR Date

What I am up to here is fetching some data from mysql table within a week from today. My only challange is that Dates are stored in VARCHAR format D M d Y.
My table stored Date example: Wed Jul 03 2016
My Code is:
$result = mysqli_query($con," SELECT * FROM `BIMTECH_academy_2016_classes` WHERE STR_TO_DATE(Date, '%D %M %d %Y') > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY Date,From DESC; ");
while($row = mysqli_fetch_array($result))
{
echo $row['ClassNumber'];
echo $row['CourseName'];
echo $row['Date'];
echo $row['From'];
echo $row['To'];
}
That's... well, a bit sad. Dates should be stored as proper data type because you can query the data without too much overhead. If there's any chance, please do convert those dates to valid date format and change the column type to date or datetime.
In the meantime, you can use MySQL's STR_TO_DATE() function, but since it would be used in WHERE part of the query, then MySQL will always scan the entire table, then internally convert all strings to dates, and only then compare with what you need. If there's a lot of data stored in a table, that can be really slow. Indexing the column won't help either, since MySQL has to fetch and convert all columns anyway before it's able to perform the comparison.
example:
just relace #date with your column name and you should get the date returned in format you want.
SET #date = "Sun Jul 10 2016";
SELECT DATE_FORMAT(STR_TO_DATE(#date,"%a %b %d %Y"),"%Y-%m-%d") as formatted_date
more details: DATE_FORMAT,STR_TO_DATE

How to fetch record by month in MySQL?

I have stored Date in database in dd-mm-yy format, for example 03-10-2013,
How to search record by month? Month in digit (01 to 12);
I am using currently
$query = "SELECT * FROM data WHERE date LIKE %$month%";
but this not working properly.
I am assuming when you say dates as stored in the database in a format, that they are not stored using a "date" type and instead are using a varchar or char type for the column.
Based on that there are few ways to do this.
Leave the database as it is and convert values on the fly.
SELECT * FROM data WHERE Month(STR_TO_DATE(datestrcolumn, '%d/%m/%Y')) = 5;
Change the type of the column to a "date" type column
SELECT * FROM data WHERE Month(realdatecolumn) = 5;
Change the type of the column to a "date" type column, store a separate column for the month.
UPDATE data set monthcolumn = Month(realdatetimecolumn)
then
SELECT * FROM data WHERE monthcolumn = 5;
Create an index on monthcolumn and this query will be much faster than the other queries if there is a lot of data
Fix the date format in your database structure first, change it to: yyyy-mm-dd
Then change your query statement to:
$query = "SELECT * FROM data WHERE MONTH(`date`) = '$month';
This will select the month as '5' or '11' or '12' which will give duplicates for differing years.
If you need the month with year (to avoid duplicate years):
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),1,7) = SUBSTR(DATE('$month'),1,7);
This will return: '2015-01' or '2014-12'
To get date as '01' or '04' or '12':
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),6,2) = SUBSTR(DATE('$month'),6,2);
Try this...
You could use MySQL MONTH() function
MySQL MONTH() returns the MONTH for the date within a range of 1 to 12 ( January to December). It Returns 0 when MONTH part for the date is 0
4 is april
SELECT * FROM tbl WHERE MONTH( date ) ='4'
You can do like it... as it is not in date format(YYYY-MM-DD)
$q="SELECT * FROM data WHERE MONTH(DATE_FORMAT(STR_TO_DATE(date, '%d-%m-%Y'), '%Y-%m-%d') ) = '$YOUR_SEARCH_MONTH' ";

PHP - MySQL query - counting results where timestamp is within specific date ("Y-m-d")

This is pretty basic MySQL, but I have not been able to figure this one out, how to do it correctly..
Example:
I have a DB table named "table1" with a list of records of user visitors data.
Columns:
"ID", "TM" and "IP"
"TM" contains timestamp for when the record is stored.
I have a PHP code where I loop through days from a start date to current day. Like this example:
// Start date
$startdateforarray = '2010-07-21';
// End date
$end_date = date("Y-m-d");
while (strtotime($startdateforarray) <= strtotime($end_date)) {
$timestamp = strtotime($startdateforarray);
//Here I want to run my MySQL Query...
$startdateforarray = date ("Y-m-d", strtotime("+1 day", strtotime($startdateforarray)));
}
Now, inside the loop I want to make a query to count how many results there are in "table1" for each day.
So the MySQL query should be something like:
"SELECT * FROM table1 WHERE TM = (day of $timestamp)"
Of course (day of $timestamp) is where I have a problem.
I know that this should be pretty simple to do, but I havent found a solution yet..
Assuming by timestamp you mean Unix Timestamp, you can do
SELECT * FROM table1 WHERE FROM_UNIXTIME(TM,'%Y-%m-%d') = '2010-07-21'

getting first 5 digits of a database stored number in the query

I'm working with a table and there is field in my table which stores raw time() function value as date.
I want to get rows with today date from this table .
So i figure out when time() func returns a 10 digit number like 1316352184 the first 5 digits are for year , month , day which i need for getting today's date and the rest is for hour minute Second which i dont need
So i get today without hour and... like
$t = time();
$t = $t /100000;
$today =(int)$t;
Now i need to get rows with today date from the table but i'm not sure how to do that.
How can i get first 5 digits of stored date in database in my query to compare it with $date?
Something like this:
$sql = "SELECT * FROM TABLE WHERE ((int)date/100000) as date = $today ;
select * from table
where from_unixtime(unix_timestamp_field,'%Y-%m-%d') = curdate()
Why you don't use:
$sql = "SELECT * FROM TABLE WHERE date(date) = date(NOW());
What you have is a UNIX timestamp. The number of seconds since January 1st, 1970.
You can use date() and mktime() to work out what todays timestamp is, then do date > the timestamp. If that make sense.
Sounds like you should use the DATETIME or TIMESTAMP data type for your column so you can use MySQL's date functions.

Getting any rows which were added before a certain date

Would this be possible? I've used this to insert the date into a field called "date":
$date=date("m/d/y");
$sql="INSERT INTO pool (date) VALUES('$date' )";
$result=mysql_query($sql);
I've used this statement to get the date a week ago:
$variable = date('d-m-y', strtotime('-1 week'));
So how would I SELECT any rows which were added last week?
Instead of storing your dates as m/d/y, you should store them as Y-m-d :
$date=date("Y-m-d");
$sql="INSERT INTO pool (date) VALUES('$date' )";
In the database, you dates will then look like 2011-04-09.
That format is much easier to work with : alphabetical comparisons will work.
Which means that searching for rows that are older than a certain date would become something like this :
$variable = date('Y-m-d', strtotime('-1 week'));
$query = "select * from pool where date < '$variable'";
Also note that instead of working with a date field which is a varchar (or an equivalent) in your database, you could use a DATE column -- which would allow to to work with date and time functions in MySQL.
If the date field is a proper date type you can do < or > in your sql query. For example -
SELECT * FROM table WHERE date > '$date'
If you want everything from 1 week ago to now you can do something like the above or
SELECT * FROM table WHERE date BETWEEN '$date' AND NOW()

Categories