2013-05-13 36 views
2
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 所有行,但它返回「1」,而我有10+行與同數據?如何從一個查詢PHP返回COUNT(*)的結果

我做錯了什麼?

這些是位於我的數據庫中的行:

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',爲什麼?

+0

返回現在什麼都沒有 – user2363542 2013-05-13 21:24:56

+0

我已經添加了我的表格外觀編輯 – user2363542 2013-05-13 21:25:21

+0

count($ result-> fetchAll())。返回所有提取的行。如果您選擇一個列而不是count(*),這將起作用。 – 2013-05-13 21:28:30

回答

2

他們包裹查詢應該是

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

該查詢工作正常!非常感謝。 – user2363542 2013-05-13 21:37:24

+0

好的,你應得的。我有點嫉妒,因爲我第一次與這個答案,我是什麼repwhore。 – 2013-05-13 21:41:28

+0

@JanTuroň:你的答案是不一樣的這個答案。注意這個查詢的SELECT子句。他想要的是實際結果,而不僅僅是COUNT。 – 2013-05-13 21:42:41

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']; 
} 
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']; 
} 
+0

這實際上並不準確。 'year'和'month'是函數 - 但是,mysql允許您使用函數名作爲列名,而不會有任何問題。請參閱http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html – 2013-05-13 22:35:27