Db: add count() helper method

This commit is contained in:
Benjamin Renard 2023-11-20 18:32:24 +01:00
parent fbd24ff1b9
commit 174ff2bb36
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC

View file

@ -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}>|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
* @var array<string,string>