如何从查询PHP返回COUNT(*)结果

时间:2013-05-13 21:21:57

标签: php mysql

public function votesThisMonth()
{
    $this->query = $this->pdo->prepare
    ("
        SELECT
            COUNT(*) AS num_votes
        FROM
            votes
        WHERE
            YEAR(year) = YEAR(CURRENT_DATE)
        AND MONTH(month) = MONTH(CURRENT_DATE)
    ");
    $result = $this->query->execute();

    return $result['num_votes'];
}

我想返回2013年和第5个月的所有行。 但是当我有10多行具有相同的数据时它返回'1'?

我做错了什么?

这些是位于我的数据库中的行:

id  ip          year    month
1   127.0.0.1   2013    5
2   127.0.0.1   2013    5
3   127.0.0.1   2013    5
4   127.0.0.1   2013    5
5   127.0.0.1   2013    5
6   127.0.0.1   2013    5
7   127.0.0.1   2013    5
8   127.0.0.1   2013    5
9   127.0.0.1   2013    5
10  127.0.0.1   2013    5
11  127.0.0.1   2013    5
12  127.0.0.1   2013    5
13  127.0.0.1   2013    5
14  127.0.0.1   2013    5
15  127.0.0.1   2013    5

编辑我的方法请看:

    public function votesThisMonth()
    {
        $this->query = $this->pdo->prepare
        ("
            SELECT
                *
            FROM
                votes
            WHERE
                YEAR(year) = YEAR(CURRENT_DATE)
            AND MONTH(month) = MONTH(CURRENT_DATE)
        ");
        $this->query->execute();

        return $this->query->rowCount();
    }

这返回'0',为什么?

3 个答案:

答案 0 :(得分:2)

查询应为

SELECT * FROM votes
WHERE `year`  = YEAR(CURRENT_DATE)
  AND `month` = MONTH(CURRENT_DATE) 

答案 1 :(得分:1)

yearmonth是关键字,无论如何,所以将它们包装在反引号中

public function votesThisMonth()
{
    $this->query = $this->pdo->prepare
    ("
        SELECT
            COUNT(*) AS num_votes
        FROM
            votes
        WHERE
            `year` = YEAR(CURRENT_DATE)
        AND `month` = MONTH(CURRENT_DATE)
    ");
    $result = $this->query->execute();

    return $result['num_votes'];
}

答案 2 :(得分:0)

你应该按照以下方式进行

public function votesThisMonth()
{
    $this->query = $this->pdo->prepare
    ("
        SELECT
            COUNT(*) AS num_votes
        FROM
            votes
        WHERE
            YEAR(year) = YEAR(CURRENT_DATE)
        AND MONTH(month) = MONTH(CURRENT_DATE)
    ");
    $this->query->execute();
    $result = $this->query->fetch(PDO::FETCH_ASSOC);

    return $result['num_votes'];
}