将此SQL语句编写为PDO查询的最佳方法是什么?我希望它以数字形式返回查询数。
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 :(得分:1)
如果要获取总行数,请使用fetchColumn函数。
还有一个更正,因为您在 ON子句中使用 JOIN ,所以不能使用变量值,只使用列名。
$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();
答案 1 :(得分:0)
请检查一下你的查询:我已经高估了你做错的情况,这将放在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 [“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->fetchAll();