首页 > 解决方案 > PHP回显已批准评论的总数给出错误

问题描述

在我当前的项目中,我有一个三元 foreach 循环来显示前五个帖子。这工作正常。在表格中,我想回应已批准评论的总数。当我尝试下面的代码时,我得到了错误Catchable fatal error: Object of class stdClass could not be converted to string

<?php
$pdo = new PDO($dsn, user, password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>

<?php
$sql = 'SELECT COUNT(*) FROM comments WHERE id =' .$post['id']. ' AND status = "ON"';
    $stmt->execute();
    $commentCount = $stmt->fetch();
    echo $commentCount;
?>

我尝试使用 array_shift 但收到另一条错误消息Warning: array_shift() expects parameter 1 to be array, object given in

<?php
$sql = 'SELECT COUNT(*) FROM comments WHERE id =' .$post['id']. ' AND status = "ON"';
   $stmt->execute();
   $commentCount = $stmt->fetch();
   $result = array_shift($commentCount);
   echo $result;
?>

由于我是 PHP 和 PDO 的新手,我很难理解我哪里出错了。有人可以指出我正确的方向吗?

标签: phpmysqlpdocount

解决方案


编辑:由于您使用 PDO,您可以使用以下内容:

<?php

$post['id'] = 1;
$stm = $pdo->prepare("SELECT COUNT(*) FROM comments WHERE id = ? AND status = ?");
$stm->bindValue(1, $post['id']);
$stm->bindValue(2, 'ON');
$stm->execute();
$countResult = $stm->fetchColumn();
echo $countResult; // Count result here

推荐阅读