Home > Blockchain >  PHP MYSQL select between dates
PHP MYSQL select between dates

Time:05-10

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related