yii\db\Query::count PHP Method

count() public method

Returns the number of records.
public count ( string $q = '*', Connection $db = null ) : integer | string
$q string the COUNT expression. Defaults to '*'. Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
$db Connection the database connection used to generate the SQL statement. If this parameter is not given (or null), the `db` application component will be used.
return integer | string number of records. The result may be a string depending on the underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
    public function count($q = '*', $db = null)
    {
        if ($this->emulateExecution) {
            return 0;
        }
        return $this->queryScalar("COUNT({$q})", $db);
    }

Usage Example

 public function actionIndex()
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     $params = Yii::$app->getRequest();
     $filter = array();
     $sort = "";
     $page = isset($params->page) ? $params->page : 1;
     $limit = isset($params->limit) ? $params->limit : 10;
     $offset = $limit * ($page - 1);
     /* Filter elements */
     if (isset($params->filter)) {
         $filter = (array) json_decode($params->filter);
     }
     if (isset($params->sort)) {
         $sort = $params->sort;
         if (isset($params->order)) {
             if ($params->order == "false") {
                 $sort .= " desc";
             } else {
                 $sort .= " asc";
             }
         }
     }
     $query = new Query();
     $query->offset($offset)->limit($limit)->from('restaurants')->orderBy($sort)->select("restaurant_id, name, street, house_nr, flat_nr, zip_code, city");
     $command = $query->createCommand();
     $models = $command->queryAll();
     $totalItems = $query->count();
     echo json_encode(array('status' => 1, 'code' => 200, 'data' => $models, 'totalItems' => $totalItems), JSON_PRETTY_PRINT);
 }
All Usage Examples Of yii\db\Query::count