diff --git a/src/Db.php b/src/Db.php index aa37e98..2e45716 100644 --- a/src/Db.php +++ b/src/Db.php @@ -196,6 +196,34 @@ class Db { return false; } + /** + * Helper to retreive a count from a table of the database + * @param string $table The table name + * @param array|string $where WHERE clause(s) as expected by Envms\FluentPDO\Query + * @param array|string|null $what What to count (optional, default: "*") + * @param array|array{0: 'LEFT'|'RIGHT'|'INNER'|'OUTER'|'FULL', 1: string, 2: string} $joins Join specification as array (see apply_joins()) + * @return array|false + */ + public function count($table, $where, $what=null, $joins=null) { + try { + $query = $this -> fpdo -> from($table) -> where($where); + if ($joins) + self :: apply_joins($query, $joins); + $query -> select(null) -> select(sprintf("COUNT(%s) as count", $what?$what:"*")); + if ($query->execute() === false) + return false; + $return = $query->fetchAll(); + if (is_array($return) && count($return) == 1) + return $return[0]["count"]; + } + catch (Exception $e) { + self :: _log_simple_select_query_error( + false, $table, $e, $where, null, null, null, $joins + ); + } + return false; + } + /** * Mapping of JOIN type with corresponding query object method * @var array