-1

I wanted to use like query together with between query...how can i combine them together? this is how I tried to do so?

$today = date('Y-m-d');
$lastWeek = date("Y-m-d", strtotime("-7 days"));
$selected_value = $search_value = $_POST["category"]; 
$sql = "SELECT * FROM work WHERE category like '%$selected_value%' AND date_added BETWEEN '" . $lastWeek . "' AND  '" . $today . "'";

what I wanted is to select all data lists from work column where category is some value and the date is inserted in the last 7 days... how can I fix this error?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Buruk
  • 49
  • 5
  • 3
    Please provide sample data and desired results. Also, learn to use parameters, rather than munging query strings with values. – Gordon Linoff Nov 16 '19 at 17:20
  • 4
    *"how can I fix this error?"* - What error is that? – Funk Forty Niner Nov 16 '19 at 17:25
  • 1
    When I use the above query I get nothing in return – Buruk Nov 16 '19 at 17:30
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Nov 16 '19 at 18:12

2 Answers2

2

Let the database do the date work:

SELECT *
FROM work
WHERE category like CONCAT('%', ?, '%') AND
     date_added >= CURDATE() - INTERVAL 6 DAY AND
     date_added <= CURDATE() ;

The ? is a parameter placeholder used to pass in a value.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-2

Little improvement of Gordon Linoff answer:

SELECT *
FROM work
WHERE category like CONCAT('%', $selected_value, '%') AND
     date_added >= CURDATE() - INTERVAL 6 DAY AND
     date_added <= CURDATE();
Tamjid Hasan
  • 129
  • 8
  • This won't even work (missing single quotes) and just introduces a security hole. The missing parenthesis is already fixed in Gordons answer. – Paul Spiegel Nov 16 '19 at 18:29