0

I have a website with a simple PHP query that return records from a MYSQL table without issue.

$query = mysqli_query( $connection, "SELECT * FROM $shopname

I am trying to figure out how to only return the last 5 days of records based on a field called "date". The date field is a VARCHAR type in mysql. The format of the dates in the date field are like this: 8/9/2016 5:52:17 PM. I did try the following query from some researching, but this doesn't return anything. What am I doing wrong?

$query = mysqli_query( $connection, "SELECT * FROM $shopname WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 5 DAY)"); 

*IMPORTANT - I can't change mysql field to DATE. It has to be VARCHAR.

Maria Nolorbe
  • 357
  • 4
  • 14

4 Answers4

1

You can use STR_TO_DATE() here for VARCHAR date format:

Example:

$query = "SELECT * FROM $shopname 
WHERE DATEDIFF(CURDATE(), STR_TO_DATE(date,'%Y-%m-%d')) < 5";

STR_TO_DATE() for DateFormat, will use to compare date with CURDATE().

DATEDIFF() for DateDiff, will use to get date difference in between date and current date.

But, it's better to use MYSQL Date format, instead of VARCHAR field.

devpro
  • 16,184
  • 3
  • 27
  • 38
1

assuming that your vatchar date column is formatted as dd-mm-yyyy you shuold convert in date this way

$query = mysqli_query( $connection, 
    " SELECT * 
      FROM $shopname 
      WHERE str_to_date(`date`, '%d-%m-%Y')  >= DATE_SUB( CURDATE(), INTERVAL 5 DAY)");
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

Try this:

SELECT * FROM TABLE t WHERE t.date >= DATE(NOW()) - INTERVAL 5 DAY

Provide the date should be if the char-type as date

Or else you can use this method to retrieve the data for last 5 days.

SELECT name,date 
from TABLE
WHERE date >= DATE_SUB(CURDATE(), INTERVAL 5 DAY) AND date <= CURDATE()
ORDER BY date DESC
Naresh Kumar P
  • 4,127
  • 2
  • 16
  • 33
0

you can use this method by mysql UNIX_TIMESTAMP.this can change time to timestamp!

$query = mysqli_query( $connection, "SELECT * FROM $shopname WHERE `date` >= UNIX_TIMESTAMP(8/9/2016 5:52:17 PM)"); 
devpro
  • 16,184
  • 3
  • 27
  • 38