简体   繁体   中英

Put a PHP variable in a SQL Query

I have the following code:

try
{
    $sql = 'SELECT id, type, date, amount, description, category 
FROM `transactions`
    WHERE type = "income"
    AND month(date) = '$monthselect'
    ORDER BY `transactions`.`id` DESC
    LIMIT 0,50';
    $result2 = $pdo->query($sql);
}

Now, I want to give this month(Date) a variable which month I want to select. if I put 1, it will give me January. So i thought, if I define a variable with 1, I can use it to select a month, right?

$monthselect = 1;

It doesnt work. What am I doing wrong?

Use prepared statements:

$stm = $pdo->prepare('SELECT id, type, date, amount, description, category 
FROM `transactions`
    WHERE type = "income"
    AND month(date) = ?
    ORDER BY `transactions`.`id` DESC
    LIMIT 0,50');

$stm->execute(compact('monthselect'));
$result2 = $stm->fetchAll();

Since you're not adding "1" directly in your query, I'm assuming here that the variable comes from user input.

To concatenate strings in PHP you need to use the . operator.

$sql = 'SELECT id, type, date, amount, description, category 
    FROM `transactions`
    WHERE type = "income"
    AND month(date) = ' . $monthselect . '
    ORDER BY `transactions`.`id` DESC
    LIMIT 0,50';

I'll frequently use double quotes to substitute variables in PHP:

$sql = "SELECT id, type, date, amount, description, category 
    FROM `transactions`
    WHERE type = 'income'
    AND month(date) = $monthselect
    ORDER BY `transactions`.`id` DESC
    LIMIT 0,50";

Note that you need to swap the existing double quotes (inside the string) to single quotes. You can escape them too, but I find this way makes it much more readable.

Your issue is that you are trying to use a variable inside single quotes, inside which php is not translated

I find by using double quote marks around my queries it allows me to not only use variables in them but to also be able to use single quote mark around the values passed to the db

$sql = "SELECT id, type, date, amount, description, category 
FROM `transactions`
WHERE type = 'income'
AND month(date) = $monthselect
ORDER BY `transactions`.`id` DESC
LIMIT 0,50";

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