将PHP变量放在SQL查询中

时间:2013-06-19 20:03:03

标签: php sql variables

我有以下代码:

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);
}

现在,我想给这个month(Date)一个变量,我要选择哪个月。如果我放1,它会给我一月。所以我想,如果我用1定义一个变量,我可以用它来选择一个月,对吗?

$monthselect = 1;

它不起作用。我做错了什么?

4 个答案:

答案 0 :(得分:3)

使用准备好的陈述:

$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();

由于您没有在查询中直接添加“1”,我假设变量来自用户输入。

答案 1 :(得分:1)

要在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';

答案 2 :(得分:1)

我会经常使用双引号来替换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";

请注意,您需要将现有的双引号(在字符串内)交换为单引号。你也可以逃避它们,但我发现这种方式使它更具可读性。

答案 3 :(得分:1)

你的问题是你试图在单引号内使用变量,其中php没有翻译

我发现在我的查询中使用双引号可以让我不仅在其中使用变量,而且还能够在传递给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";