简体   繁体   中英

PHP MYSQL select between dates

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM