/**
 * Perform a count query on the database and return the count
 *
 * @param string        $arg1 The SQL query string or table name
 * @param string|array  $arg2 The field name to count on
 *   or the array of placeholders and their values if the first argument is SQL
 *
 *      array(
 *          ':placeholder1' => $value1,
 *          ':placeholder2' => $value2
 *      )
 *
 * @param string|null   $arg3 The field alias if the first argument is table name
 *   or the second argument is field name
 *
 * @return int|object The result count or QueryBuilder
 */
function db_count($arg1, $arg2 = null, $arg3 = null)
{
    if ($arg1 && QueryBuilder::validateName($arg1)) {
        $table = $arg1;
        $alias = 'count';
        $qb = new QueryBuilder($table);
        if ($arg3 && QueryBuilder::validateName($arg3)) {
            $alias = $arg3;
        }
        if ($arg2 && QueryBuilder::validateName($arg2)) {
            $field = $arg2;
            $qb->count($field, $alias);
        } else {
            $qb->count('*', 'count');
        }
        return $qb;
    } else {
        $sql = $arg1;
        $args = $arg2;
        if ($result = db_fetch($sql, $args)) {
            return $result;
        }
    }
    return 0;
}