[英]Array to string conversion error?
I am using PDO and trying to display how many users are in a table, however I get this error: 我正在使用PDO并尝试显示表中有多少用户,但是出现此错误:
Notice: Array to string conversion in C:\Users\admin.phtml on line 10 Array
Then in my Admin class: 然后在我的管理类中:
public function CountUsers()
{
$query = "SELECT * FROM Users";
$statement = $this->_dbHandle->prepare($query);
// Then execute the query
$statement->execute();
// This will return the row from the database as an array
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
Then in my Admin Controller I have: 然后在我的管理控制器中:
$Admin = new Admin();
$CountUsers = $Admin->CountUsers();
To display the results I have this in my phtml: 为了显示结果,我在phtml中有以下内容:
<var><?php echo $CountUsers; ?></var>
Does anyone understand what I am doing wrong? 有人知道我在做什么错吗?
You should try to count the users in query, like so: 您应该尝试计算查询中的用户,如下所示:
public function CountUsers() {
$query = "SELECT COUNT(1) FROM Users";
$statement = $this->_dbHandle->prepare($query);
if($statement->execute()) {
// This will return COUNT(1) field
return $statement->fetch(PDO::FETCH_NUM)[0];
}else{
return 0; // should the query fail, return 0
}
}
If you want to stick to counting in PHP (which you shouldn't), modify your code to do: 如果您想坚持使用PHP进行计数(不应该这样做),请修改代码以执行以下操作:
return count($statement->fetchAll(PDO::FETCH_ASSOC));
But you shouldn't query all of the data just to count and discard it. 但是您不应该仅查询和丢弃所有数据。 Using SQL's
count
is far more performant for several reasons: 使用SQL
count
性能要好得多,原因有以下几个:
fetchAll
, it will store all of the data into PHP array, taking up memory fetchAll
,它将所有数据存储到PHP数组中,占用内存 To display a meaningful text, or do something with this function you can: 要显示有意义的文本或使用此功能执行某些操作,您可以:
function CheckUsers() {
$userCount = CountUsers();
if($userCount == 0) {
echo 'No users found';
}else{
echo $userCount . ' users found';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.