简体   繁体   中英

Using COUNT and inner join in PDO query

What would be the best way of writing this SQL statement as a PDO query? I want it to return the number of queries as a number.

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

This is what I was thinking:

$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();

If you want to get the total number of rows, use fetchColumn function.

And one more correction, since you are using JOIN here so in the ON clause , you can't use the variable value, use column name only.

$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();

Please check your query once:I have highlited the condition ehich you doing wrong this will be put in where clause .

  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

I guess your code will be look like this:

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM