0

I have a little simple problem. I want to perform a query on a Mysql table to select posts posted after a certain date but I don't manage to get it working by setting that date as a PHP variable.

The following query doesn't return anything:

$reqsql = "SELECT * FROM posts WHERE post_date <= " . $from_date;

The "post_date" field is set as a datetime. I have tried everything for the $from_date PHP variable format:

$from_date = date();
$from_date = date('Y-m-d-H-i-s');
$from_date = date('Y-m-d H:i:s');
$from_date = strtodate("now");

None of these work...

But it works fine if I put a basic Mysql date like:

$reqsql = "SELECT * FROM posts WHERE post_date <= NOW()";

Any idea? Thanks!

gwendall
  • 920
  • 15
  • 22

4 Answers4

5

You probably only need to wrap $from_date in single quotes.

$reqsql = "SELECT * FROM posts WHERE post_date <= '" . $from_date ."'";
dee-see
  • 23,668
  • 5
  • 58
  • 91
2

Put the date between quotes:

$reqsql = "SELECT * FROM posts WHERE post_date <= '" . $from_date . "'";
nobody
  • 10,599
  • 4
  • 26
  • 43
1

You need to use the date like any other string in your query:

$reqsql = "SELECT * FROM posts WHERE post_date <= '" . $from_date . "'";
Wesley van Opdorp
  • 14,888
  • 4
  • 41
  • 59
0

You could pass the date from PHP in UNIX-time format using time() and then run FROM_UNIXTIME() on it in the SQL query.

Jonatan
  • 2,734
  • 2
  • 22
  • 33