0

将此 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();
4

2 回答 2

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();
于 2013-02-15T16:39:03.197 回答
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["房间"];

$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();
于 2013-02-15T15:37:40.853 回答