php - 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 的新手,我很难理解我哪里出错了。有人可以指出我正确的方向吗?
解决方案
编辑:由于您使用 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
推荐阅读
- google-sheets - 下一个可用行中的 Google 表格增量公式
- html - 未定义变量 $alert-padding-y
- python - AWS Glue 数据从 S3 迁移到 Redshift
- javascript - 在mongodb中查找元素的父级
- php - 有人可以向我解释 $_POST['var1'] 在此示例中如何分配给 $m_value
- next.js - 首次尝试 Vercel 部署失败时无法打开构建日志
- java - com.maverick.ssh.SshException:密钥交换失败:预期 SSH_MSG_KEX_GEX_GROUP [id=3]
- java - Jenkins Down - “设备上没有剩余空间”错误
- amazon-web-services - 订阅错误
:从数据存储同步模型时出现 GraphQLResponse.Error - python - 一个简单的 python 代码将用于迭代的循环变量与常量变量相乘会产生意想不到的结果