简体   繁体   中英

How to Refer to a count(*) column in a PDO Query

$stmt = $con->prepare("SELECT t.name, COUNT(*) 
                        FROM team t
                        JOIN member m ON FIND_IN_SET( m.team_id, t.id ) >0
                        GROUP BY t.name
                        LIMIT 0 , 30");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn('count', $count);
$stmt->bindColumn('name', $name);
while ($row = $stmt->fetch()) 
{
     echo "<tr><td>".$name."</td>";                   
    echo "<td>".$count."</td>";
 }

The code above retrieves 2 columns: name and the count(*) . The problem is with accessing the count column; I get the below error.

Warning: PDOStatement::bindColumn(): SQLSTATE[HY000]: General error: Did not find column name 'count' in the defined columns; it will not be bound in

How can I bind to that total count?

Use an alias: COUNT(*) as count .

$stmt = $con->prepare("SELECT t.name, COUNT(*) as count
                        FROM team t
                        JOIN member m ON FIND_IN_SET( m.team_id, t.id ) >0
                        GROUP BY t.name
                        LIMIT 0 , 30");

$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn('count', $count);
$stmt->bindColumn('name', $name);

while ($row = $stmt->fetch()) 
{
    echo "<tr><td>".$name."</td>";                   
    echo "<td>".$count."</td>";
}

Instead of using aliases with column names, you can specify the column number (starting from 1).

$stmt = $con->prepare("SELECT t.name, COUNT(*) 
                        FROM team t
                        JOIN member m ON FIND_IN_SET( m.team_id, t.id ) >0
                        GROUP BY t.name
                        LIMIT 0 , 30");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn(2, $count);
$stmt->bindColumn(1, $name);

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