简体   繁体   中英

How to select rows that have a column that matches a value and fall between a date range using PHP's PDO and MySQL?

Can someone help me with my query below? I need to select all users who subscribe to the "Food Specials" newsletter (that has to be passed in through a form variable because there are different newsletter names) and have a value of "1" and that fall between the sign up dates that were selected in a form:

$sql = 'SELECT * FROM users WHERE :newsletter = 1 AND signed_up < ":start" AND signed_up < ":end"';
$result->bindValue(":newsletter", "food_specials", PDO::PARAM_STR);
$result->bindValue(":start", "2012-09-01 12:00:00", PDO::PARAM_STR);
$result->bindValue(":end", "2012-09-25 12:00:00", PDO::PARAM_STR);

First "food_specials" will never equal 1. You should probably bind a variable containing the value 1 here or something. Not sure what it's for. For the rest of this answer I'm going to assume food_special is the column name that you're trying to set with pdo. This cannot be done. What you need to do is just explicitly put it in the sql. See example below.

You also need to change

signed_up < ":start" 

to

signed_up > :start

Ie what you need is

$sql = "SELECT * 
          FROM users 
         WHERE food_special = 1 
           AND signed_up > :start 
           AND signed_up < :end";

If by signed_up > :start AND signed_up < :end you actually meant signed_up >= :start AND signed_up <= :end then you should look @glavić's answer for an alternative solution.

Use BETWEEN :

SELECT * 
FROM users 
WHERE 
    :newsletter = 1 AND 
    signed_up BETWEEN :start AND :end

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