2025-08-02 15:45:51 +03:00

80 lines
3.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* @noinspection SqlNoDataSourceInspection
*/
namespace goodboyalex\php_db_components_pack\traits\Database;
use goodboyalex\php_db_components_pack\classes\ConditionBuilder;
use goodboyalex\php_db_components_pack\enums\DBDriver;
use PDO;
/**
* Трейт для подсчета количества записей в таблице базы данных и проверки существования записи.
*
* @author Александр Бабаев
* @package php_db_components_pack
* @version 1.0
* @since 1.0
* @see PDO
*/
trait DatabaseCountExist
{
/**
* Подсчитывает количество строк, удовлетворяющих условию.
*
* @param string $table Имя таблицы.
* @param ConditionBuilder $where Условия выборки.
*
* @return int Количество строк или -1, в случае ошибки.
*/
public function Count (string $table, ConditionBuilder $where): int
{
/**
* Получаем условия.
*
* @var string $sql_where Строка WHERE условий.
* @var array $params Параметры условий.
*/
[$sql_where, $params] = $where->Build();
// Создаю запрос
$sql = "SELECT COUNT(*) FROM $this->DBSignOpen$table$this->DBSignClose";
// Если заданы where-параметры
if ($where->Count() > 0)
// - то добавляю их
$sql .= ' WHERE ' . $sql_where;
// Выполняю запрос
$countResult = $this->Query($sql, $params);
// Если запрос выполнен с ошибкой
if ($countResult === false)
// - то в результат идёт -1
return -1;
// Получаю секцию
$section = match ($this->Config->Driver) {
DBDriver::MySQL, DBDriver::SQLite => "COUNT(*)",
DBDriver::MSSQL, DBDriver::OracleDB, DBDriver::PostgreSQL => ""
};
// Вывожу количество
return isset($countResult[0][$section]) ? (int)$countResult[0][$section] : -1;
}
/**
* Проверяет, существует ли запись в таблице.
*
* @param string $table Имя таблицы.
* @param ConditionBuilder $where Условия выборки.
*
* @return bool Результат проверки.
*/
public function IsExist (string $table, ConditionBuilder $where): bool
{
// Вывожу результат
return $this->Count($table, $where) > 0;
}
}