当我用PDO重写代码时,Count不起作用

时间:2014-11-06 07:00:43

标签: php html mysql pdo

一旦我从mysql更改为pdo,我无法完成工作。我不知道该怎么做。

<tr>
    <td style="width: 125px">
        <a href="SystemsTechsPages/xgrh/xgrhCompleted1.php" target="_top">xgrh</a>
    </td>
    <td style="width: 125px" align="center">
        <a href="SystemsTechsPages/xgrh/xgrhCompleted1.php" target="_top">
        <?php 

        $stmt = $db->prepare("
            SELECT COUNT(*) FROM WHERE requests status='Completed' AND compDT=Curdate() AND compUser='xgrh'
        ");  
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
            echo $row['COUNT(*)'];  
        }  
        ?>
        </a>
    </td>
</tr>

4 个答案:

答案 0 :(得分:3)

首先,确保查询正确:

缺少一个表名

SELECT COUNT(*) FROM (what happened here? no table name)

WHERE status='Completed' 
AND compDT=Curdate() 
AND compUser = 'xgrh'

其次,您可以使用别名来更好地访问列名称:

<?php 
// prepare
$stmt = $db->prepare("
    SELECT COUNT(*) AS total FROM table_name 
    WHERE status='Completed' 
    AND compDT = Curdate() 
    AND compUser = 'xgrh'
");
$stmt->execute(); // execute
$result = $stmt->fetch_assoc(PDO::FETCH_ASSOC);
$count = $result['total'];
echo $count;

?>

答案 1 :(得分:2)

您应该更改查询:

SELECT COUNT(*) AS rows_cnt FROM table WHERE  status='Completed' AND compDT=Curdate() AND compUser='xgrh'

然后:

并像这样使用它:

$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{ 
   echo $row['rows_cnt'];  
}

答案 2 :(得分:2)

您应该在获取之前调用$stmt->execute()。准备好的STMT不会发送到服务器,您应该使用execute发送它。

答案 3 :(得分:0)

您可以像这样在PDO中获取行数:

$count = $stmt->rowCount();