Db: add count() helper method
This commit is contained in:
parent
fbd24ff1b9
commit
174ff2bb36
1 changed files with 28 additions and 0 deletions
28
src/Db.php
28
src/Db.php
|
@ -196,6 +196,34 @@ class Db {
|
||||||
return false;
|
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}>|array{0: 'LEFT'|'RIGHT'|'INNER'|'OUTER'|'FULL', 1: string, 2: string} $joins Join specification as array (see apply_joins())
|
||||||
|
* @return int|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
|
* Mapping of JOIN type with corresponding query object method
|
||||||
* @var array<string,string>
|
* @var array<string,string>
|
||||||
|
|
Loading…
Reference in a new issue