user2562125
user2562125

Reputation: 175

Mysql query with multiple year intervals

I have created a few drop down boxes that allow users to narrow down the data they are looking for. Two of the drop down boxes involve where the users select years. For example, the first box could be 1990, and the second box could be 2000. Now how to I set up a query that allows this interval of time to be applied?

$pYear1 = the first year they select in the drop down box 
$pYear2 = the second year they select in the drop down box 

select * from table where year = '$pYear1 - $pYear2';

I tried this but it didn't work. Can anyone help me with this?

Upvotes: 0

Views: 288

Answers (3)

lexmihaylov
lexmihaylov

Reputation: 737

Try using BETWEEN

select * from table where year BETWEEN '$pYear1' AND '$pYear2';

UPDATE:

As @SylvainLeroux suggested, it is highly recommended to use pdo or mysqli for performance and security reasons:

PDO Manual

MySQLi Manual

Upvotes: 1

Sylvain Leroux
Sylvain Leroux

Reputation: 52020

As I noticed in a comment, you should never ever directly inject user provided values in an SQL query.

As you are using PHP, the preferred way of doing is probably to use a prepared statement. Here I use PDO (assuming your "years" are integers):

$sth = $dbh->prepare('* from table where year BETWEEN :start_year AND :end_year;');
$sth->bindParam(':start_year', $pYear1, PDO::PARAM_INT);
$sth->bindParam(':end_year', $pYear2, PDO::PARAM_INT);
$sth->execute();

This is only an example. Several variations are available. See http://www.php.net/manual/en/pdostatement.execute.php

Upvotes: 1

Orangepill
Orangepill

Reputation: 24655

Or if you want the range excluding the date you can just do this.

select * from table where year > '$pYear1' and year < '$pYear2';

Upvotes: 0

Related Questions