2015-07-13 46 views
0

你好,我有這個表獲取與日期過濾計數發生

table name : addresses 


| id |branch |  datetime  | 
____________________________________ 

|16875 |north | 2015-07-13 02:11:34| 
|16345 |north | 2015-07-11 08:04:42| 
|16000 |north |2015-07-10 08:16:07 | 
|16960 |north |2015-07-13 05:16:04 | 
|15909 |north |2015-07-10 05:16:05 | 
|16669 |south |2015-07-12 07:16:03 | 
|16513 |south |2015-07-12 00:20:43 | 
|16699 |south |2015-07-12 08:16:02 | 
|15939 |east |2015-07-10 06:16:05 | 
|16449 |east |2015-07-11 11:16:04 | 
|16517 |east |2015-07-12 01:16:01 | 
|16729 |east |2015-07-12 09:16:02 | 
|16418 |west |2015-07-11 10:18:16 | 
|15971 |west |2015-07-10 07:16:04 | 
|16785 |west |2015-07-12 11:16:01 | 
|16757 |west |2015-07-12 10:16:02 | 
|16353 |west |2015-07-11 08:16:04 | 
|16877 |west |2015-07-13 02:16:03 | 

在我的PHP頁面,我想查詢該表,但只顯示重複值的計數,因爲我有日期時間列我要挑日期並顯示該日期的重複值。

例如是我挑日期

2015-07-12

所以我會查詢

|Branch|count| 
______________ 
|north | 2 | 
|west | 1 | 
______________ 

另一個例子是我要挑日期是

它會詢問

|Branch|count| 
______________ 
|north | 2 | 
|east | 1 | 
|west | 1 | 
______________ 

我的PHP頁面上我使用此代碼

<table cellpadding="0" cellspacing="0" border="0" id="table"> 
     <thead> 
      <tr> 
       <th><h3>Branch</h3></th> 
       <th><h3>Count</h3></th> 



      </tr> 
     </thead> 
     <tbody> 
      <?php 
// Connect to database server 
mysql_connect("localhost", "user", "user") or die (mysql_error()); 

// Select database 
mysql_select_db("data") or die(mysql_error()); 

// SQL query 
$strSQL = "SELECT branch,count(branch) as occurence FROM `addresses` WHERE datetime >= \"2015-07-10\" AND datetime < \"2015-07-11\" group by branch"; 

// Execute the query (the recordset $rs contains the result) 
$rs = mysql_query($strSQL); 

// Loop the recordset $rs 
while($row = mysql_fetch_array($rs)) { 

    // W 
    echo"<tr>"; 

    echo"<td>". $row['branch']; 
    echo"<td>". $row['occurence']; 





    } 

// Close the database connection 
mysql_close(); 
        ?> 

和我的輸出是

|Branch|count| 
______________ 
|north | 2 | 
|east | 1 | 
|west | 1 | 
______________ 

所以,我怎麼能整合日期過濾我的PHP頁面上?計數重複值。

謝謝

+5

真的沒有清楚你的問題你想要什麼? – Sadikhasan

+0

嗨,對不起,如果你實際上沒有得到我的問題,我已經計數的值在我想要使用SQL查詢的範圍的日期時間上具有相同的值。 但我想要的是使用我的PHP頁面及時設置日期。 –

+0

@CarlvicJapitanaLim我的回答如何?它有幫助嗎? –

回答

1

您可以通過fromto日期作爲參數查詢:

// Connect to database 
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'password'); 

// Prepare statement 
$stmt = $dbh->prepare("SELECT branch, count(branch) AS occurence 
         FROM `addresses` 
         WHERE datetime >= :from AND datetime < :to 
         GROUP BY branch"); 

// Bind parameters 
$stmt->bindParam(':from', $from); 
$stmt->bindParam(':to', $to); 

// Execute 
$from = '2015-07-10'; 
$to = '2015-07-11'; 
$stmt->execute(); 

// Fetch result 
$result = $stmt->fetchAll(); 

更多信息,請參見PHP documentation on Prepared Statements

+0

嗨,我嘗試這段代碼,但它顯示一個錯誤 致命錯誤:無法通過引用 –

+0

傳遞參數2我修改了我的答案,在'bindParam()'之外設置'$ from'和'$ to'。 –