2013-02-15 50 views
0

將此SQL語句作爲PDO查詢編寫的最佳方式是什麼?我希望它將查詢的數目作爲數字返回。在PDO查詢中使用COUNT和內部聯接

SELECT COUNT(*) totalCount 
FROM ts_room a 
     INNER JOIN ts_roompref b 
      ON a.id = b.room_ID 
     INNER JOIN ts_request c 
      ON b.request_ID = c.roompref_ID 
WHERE c.day_ID = 1 AND c.period_ID = 1 

這是我的想法是:

$room_ID = $_POST["room"]; 

$sql = "SELECT COUNT(*) totalCount 
FROM ts_room a 
     INNER JOIN ts_roompref b 
      ON a.id = b.:room_ID 
     INNER JOIN ts_request c 
      ON b.request_ID = c.roompref_ID 
WHERE c.day_ID = 1 AND c.period_ID = 1"; 

$stm = $pdo->prepare($sql); 
$stm->execute(array(':room_ID' => $room_ID)); 
$rows = $stm->fetchAll(); 

// echo row count here 
$count = $stm->rowCount(); 
+0

PDO與此有什麼關係?無論您使用的是哪個數據庫庫,查詢都是查詢。唯一的區別是你如何嵌入外部數據(例如$ _POST值)。 – 2013-02-15 15:22:54

+0

@MarcB我不是100%確定如何回顯行計數 – methuselah 2013-02-15 15:25:15

+0

從文檔開始:http://www.php.net/manual/en/pdostatement.fetchall.php – 2013-02-15 15:28:57

回答

1

如果要獲取總行數,請使用fetchColumn函數。

還有一修正,因爲你正在使用JOIN這裏,所以在ON子句,則不能使用變量值,只能使用列名。

$room_ID = $_POST["room"]; 

$sql = "SELECT COUNT(*) totalCount 
FROM ts_room a 
     INNER JOIN ts_roompref b 
      ON a.id = b.room_ID 
     INNER JOIN ts_request c 
      ON b.request_ID = c.roompref_ID 
WHERE c.day_ID = 1 AND c.period_ID = 1 and b.room_ID=:room_ID"; 

$stm = $pdo->prepare($sql); 
$stm->execute(array(':room_ID' => $room_ID)); 
$rows = $stm->fetchColumn(); 
0

請檢查一次您的查詢:我有反白標明EHICH你做錯了這種狀況將放在where子句。

SELECT COUNT(*) totalCount 
    FROM ts_room a 
      INNER JOIN ts_roompref b 
       // ON a.id = b.:room_ID 
      INNER JOIN ts_request c 
       ON b.request_ID = c.roompref_ID 
    WHERE c.day_ID = 1 AND c.period_ID = 1 

我想你的代碼將是這個樣子:

$ ROOM_ID = $ _ POST [ 「房間」];

$sql = "SELECT COUNT(*) totalCount 
FROM ts_room a 
     INNER JOIN ts_roompref b 
      ON a.id = b.room_ID 
     INNER JOIN ts_request c 
      ON b.request_ID = c.roompref_ID 
WHERE c.day_ID = 1 AND c.period_ID = 1 and b.room_ID=:room_ID"; 

$stm = $pdo->prepare($sql); 
$stm->execute(array(':room_ID' => $room_ID)); 
$rows = $stm->fetchAll(); 
+0

我如何得到行數?我只是回聲$行? – methuselah 2013-02-15 15:43:54