简体   繁体   English

数组到字符串的转换错误?

[英]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性能要好得多,原因有以下几个:

  • You don't fetch the actual data. 您没有获取实际数据。 If your data set is big, you have to transfer megabytes or gigabytes over sockets. 如果您的数据集很大,则必须通过套接字传输兆字节或千兆字节。 Which is not too good idea, even if the database is on the same machine. 即使数据库位于同一台计算机上,这也不是一个好主意。
  • You don't store the data in PHP. 您不将数据存储在PHP中。 When using fetchAll , it will store all of the data into PHP array, taking up memory 使用fetchAll ,它将所有数据存储到PHP数组中,占用内存
  • MySQL engine might use optimisations which further speed things up (looking up the record count directly) MySQL引擎可能会使用优化来进一步加快处理速度(直接查询记录数)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM