-1

im trying to select date from mysql between dates with this code

    if(isset($_REQUEST['datefrom']) and $_REQUEST['datefrom']!=""){
        $condition  .=  ' AND date LIKE "%'.$_REQUEST['datefrom'].'%" ';
    }
    if(isset($_REQUEST['dateto']) and $_REQUEST['dateto']!=""){
        $condition  .=  ' AND date LIKE "%'.$_REQUEST['dateto'].'%" ';
    }

Please help THX

miko
  • 11
  • 2
  • "I'm trying" isn't an error message or problem statement. It hints that you had an issue, but doesn't tell us specifically what it is. Don't expect/imagine that we can automatically/magically guess the issue. Tell us exactly what the problem is. Explain precisely what result you expected, and precisely what the code did instead of that. We don't know what's in your database, or what's in your REQUEST variables, or what output your code produced. See also [ask] and the [tour]. – ADyson May 10 '22 at 13:15
  • 3
    However, a comment: I dread to think why you're using LIKE with a date or what you think it's doing...please tell me you're not storing dates as strings/varchar in your database? If you are, that's a fundamental design mistake which will prevent you from achieving your stated goal (or getting data from _between_ two dates) easily. The `date` and `datetime` column types exist for a reason...use them. And then learn about `BETWEEN`. – ADyson May 10 '22 at 13:17
  • 4
    Also, your code is vulnerable to SQL injection becuse you're injecting user-generated data directly into your SQL string. Read [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) and learn how to write your queries far more reliably and far more safely. Don't try to run before you can walk - it seems you need to firm up your understanding of some basic principles here (in SQL and PHP) in order to know how to correctly accomplish your task. – ADyson May 10 '22 at 13:19

2 Answers2

0

Assuming your date are timestamps, date, etc. This is the most secure way to prevent SQL injection, using PHP PDO.

<?php
$dbh = new PDO('your_server', 'your_user', 'your_password');

$sth = $dbh->prepare('SELECT * FROM table WHERE date BETWEEN :from AND :to');

// Bind date params
$sth->bindParam('from', $_REQUEST['datefrom']);
$sth->bindParam('to', $_REQUEST['dateto']);

// Execute query
$sth->execute();

// This a test
print_r($sth->fetchAll());
?>

More here.

Luca Murante
  • 317
  • 3
  • 8
0

It seems you are trying to use the LIKE operator because your dates are stored as strings in your database.

You should convert them to dates, then you can just use the BETWEEN operator with them. It shouldn't be too dificult and I'm sure you can find how to do it in this site. I suggest that you do it by storing the conversion in a new column first.