this is my problem:
I have a table in my mysql database which contains some products, and it has two columns called “date_from” and “date_to” which determine the period when the product is active.
On my website a have a form where the admin can choose two datetime values and if the product’s active period intersects the span that the admin chose, the page updates a product list.
This is my query, which I am using to achieve what I want:
$sql="SELECT * FROM presents WHERE (date_from>".$date_from." AND date_to<".$date_to.") OR (date_from>".$date_from." AND date_to>".$date_to.") OR (date_from<".$date_from." AND date_to>".$date_to.") OR (date_from<".$date_from." AND date_to<".$date_to.")";
I get this error though:
mysql said: MySql error number: 1064 MySql error decription: You have
an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ‘.26. 12:11:43
AND date_to<2012.07.30. 12:11:46) OR (date_from>2012.07.26. 12:11:’ at
line 1
Any ideas?
*EDIT
I changed the query as suggested and added single quotes to variables. Now I don’t get the error, but the query doesn’t seem to do what it’s supposed to – the product list stayes the same… Here’s the query now:
$sql="SELECT * FROM presents WHERE (date_from>'".$date_from."' AND date_to<'".$date_to."') OR (date_from>'".$date_from."' AND date_to>'".$date_to."') OR (date_from<'".$date_from."' AND date_to>'".$date_to."') OR (date_from<'".$date_from."' AND date_to<'".$date_to."')";
Let’s say I have this row in my table:
ID Name date_from date_to
1 test 2012-07-24 16:40:00 2012-07-31 16:40:00
I need all of these periods to return the row:
2012-07-23 16:40:00 to 2012-08-01 16:40:00
2012-07-23 16:40:00 to 2012-07-28 16:40:00
2012-07-26 16:40:00 to 2012-07-28 16:40:00
2012-07-26 16:40:00 to 2012-08-01 16:40:00
You need to quote your variable.
But it is better not to concat sql, use placeholders instead.