Joe C Joe C - 1 month ago 21
MySQL Question

In CakePHP 3.x how can I count the number of rows in a MySql table?

I have a MYSQL table called 'devices'. I've successfully done the bin/cake bake all. In fact I have the auto-built DevicesController.php fully working. But I can't figure out how to count the rows in a table. I've tried:

$conn = ConnectionManager::get('default');
$numRows = $conn->execute('select count(*) from devices');


and

$this->DeviceSetups = TableRegistry::get('Devices');
$numRows = $this->Devices->query('select count(*) from devices'); // both like this
$numRows = $this->Devices->query('select count(*) from devices')->execute(); // and like this


and

$this->DeviceSetups = TableRegistry::get('Devices');
$numRows = $this->Devices->find('count');


Going thru mysql_query() isn't really a good idea because I have all the access info already setup in app.php for CakePHP to use. I tried something else using AnyModel that didn't work.

The former 2 attempts return a Cake\Database\Statement\MysqlStatement not an integer with the number of rows in the table. I've consulted this answer and this answer and read the CakePHP docs. Nothing seems to tell me how to count up a table nor how to execute a raw My SQL command string and then access the result.

Answer
Comments