1

我有以下代码:

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

4 回答 4

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”,因此我在这里假设变量来自用户输入。

于 2013-06-19T20:04:50.733 回答
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';
于 2013-06-19T20:04:05.640 回答
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";

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

于 2013-06-19T20:06:31.973 回答
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";
于 2013-06-19T20:08:26.093 回答