user4397029
user4397029

Reputation:

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:

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:

<var><?php echo $CountUsers; ?></var>

Does anyone understand what I am doing wrong?

Upvotes: 2

Views: 1360

Answers (1)

Sebi
Sebi

Reputation: 1436

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:

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:

  • 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. When using fetchAll, it will store all of the data into PHP array, taking up memory
  • MySQL engine might use optimisations which further speed things up (looking up the record count directly)

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';
    }
}

Upvotes: 2

Related Questions