PHPackages                             krzysztofzylka/database-manager - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. krzysztofzylka/database-manager

ActiveLibrary[Database &amp; ORM](/categories/database)

krzysztofzylka/database-manager
===============================

Database Manager

1.1.17(2mo ago)11.9k↓37.5%[2 issues](https://github.com/krzysztofzylka/DatabaseManager/issues)2MITPHPPHP &gt;=8.1

Since Dec 25Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/krzysztofzylka/DatabaseManager)[ Packagist](https://packagist.org/packages/krzysztofzylka/database-manager)[ RSS](/packages/krzysztofzylka-database-manager/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (74)Used By (2)

DatabaseManager
===============

[](#databasemanager)

Wydajna biblioteka PHP do zarządzania operacjami bazodanowymi. Wspiera MySQL i SQLite, oferując wysoką wydajność oraz czytelny interfejs.

[![MIT License](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/6b84e9311750c972da98b6d521269a76c32b8928b672000d4a8c5dd7ac866d09/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e312d626c75652e737667)](https://www.php.net/releases/8.1/en.php)

Wymagania
---------

[](#wymagania)

- PHP 8.1 lub nowszy
- Rozszerzenie PDO
- MySQL lub SQLite

Instalacja
----------

[](#instalacja)

```
composer require krzysztofzylka/database-manager
```

Podstawowe użycie
-----------------

[](#podstawowe-użycie)

### Nawiązywanie połączenia

[](#nawiązywanie-połączenia)

```
$databaseManager = new \krzysztofzylka\DatabaseManager\DatabaseManager();

try {
    $connect = \krzysztofzylka\DatabaseManager\DatabaseConnect::create()
        ->setType(\krzysztofzylka\DatabaseManager\Enum\DatabaseType::mysql)
        ->setDatabaseName('database')
        ->setUsername('username')
        ->setPassword('password');

    $databaseManager->connect($connect);
} catch (\krzysztofzylka\DatabaseManager\Exception\DatabaseManagerException $exception) {
    die($exception->getHiddenMessage());
}
```

### Operacje CRUD

[](#operacje-crud)

#### Pobieranie danych

[](#pobieranie-danych)

```
// Pobranie jednego rekordu
$table = new \krzysztofzylka\DatabaseManager\Table('users');
$user = $table->find(['id' => 1]);

// Pobranie wszystkich rekordów
$users = $table->findAll();

// Liczenie rekordów
$count = $table->findCount(['status' => 'active']);

// Sprawdzenie istnienia
$exists = $table->findIsset(['email' => 'example@domain.com']);
```

#### Dodawanie rekordów

[](#dodawanie-rekordów)

```
$table = new \krzysztofzylka\DatabaseManager\Table('users');
$table->insert([
    'username' => 'john_doe',
    'email' => 'john@example.com',
    'created_at' => date('Y-m-d H:i:s')
]);

// Pobranie ID nowo utworzonego rekordu
$newId = $table->getId();
```

#### Aktualizacja rekordów

[](#aktualizacja-rekordów)

```
$table = new \krzysztofzylka\DatabaseManager\Table('users');
$table->setId(1)->update([
    'username' => 'updated_username',
    'last_login' => date('Y-m-d H:i:s')
]);

// Aktualizacja pojedynczej kolumny
$table->setId(1)->updateValue('status', 'inactive');
```

#### Usuwanie rekordów

[](#usuwanie-rekordów)

```
$table = new \krzysztofzylka\DatabaseManager\Table('users');
$table->delete(1); // Usunięcie po ID

// Usuwanie według warunków
$table->deleteByConditions(['status' => 'deleted']);
```

### Zaawansowane zapytania

[](#zaawansowane-zapytania)

#### Złożone warunki wyszukiwania

[](#złożone-warunki-wyszukiwania)

```
// Proste warunki z operatorami
$conditions = [
    new \krzysztofzylka\DatabaseManager\Condition('age', '>', 18),
    new \krzysztofzylka\DatabaseManager\Condition('status', 'IN', ['active', 'pending']),
    'is_verified' => true
];

$results = $table->findAll($conditions);
```

#### Złączenia tabel

[](#złączenia-tabel)

```
$table = new \krzysztofzylka\DatabaseManager\Table('users');

// Podstawowe złączenie
$table->bind(
    \krzysztofzylka\DatabaseManager\Enum\BindType::leftJoin,
    'orders',
    'users.id',
    'orders.user_id'
);

// Złączenie z aliasem tabeli
$table->bind(
    \krzysztofzylka\DatabaseManager\Enum\BindType::leftJoin,
    'orders',
    'users.id',
    'orders.user_id',
    null,
    'o'  // Alias tabeli
);

// Złączenie z warunkiem
$table->bind(
    \krzysztofzylka\DatabaseManager\Enum\BindType::leftJoin,
    'orders',
    'users.id',
    'orders.user_id',
    ['status' => 'completed']  // Warunek w JOIN
);

// Złączenie z aliasem i warunkiem
$table->bind(
    \krzysztofzylka\DatabaseManager\Enum\BindType::leftJoin,
    'orders',
    'users.id',
    'orders.user_id',
    ['status' => 'completed'],
    'completed_orders'
);

$userWithOrders = $table->findAll();
```

#### Typy złączeń

[](#typy-złączeń)

```
// INNER JOIN - tylko pasujące rekordy
$table->bind(BindType::innerJoin, 'orders', 'users.id', 'orders.user_id');

// LEFT JOIN - wszystkie użytkowniki, nawet bez zamówień
$table->bind(BindType::leftJoin, 'orders', 'users.id', 'orders.user_id');

// RIGHT JOIN - wszystkie zamówienia, nawet bez użytkowników
$table->bind(BindType::rightJoin, 'orders', 'users.id', 'orders.user_id');

// CROSS JOIN - iloczyn kartezjański
$table->bind(BindType::crossJoin, 'categories', null, null);

// FULL OUTER JOIN - wszystkie rekordy z obu tabel
$table->bind(BindType::fullJoin, 'orders', 'users.id', 'orders.user_id');
```

#### Relacje

[](#relacje)

```
// Relacja hasOne - jeden do jednego
$table->bind(BindType::hasOne, 'profiles', 'users.id', 'profiles.user_id');

// Relacja hasMany - jeden do wielu
$table->bind(BindType::hasMany, 'orders', 'users.id', 'orders.user_id');
```

#### Złożone złączenia

[](#złożone-złączenia)

```
// Wielokrotne złączenia
$table->bind(BindType::leftJoin, 'orders', 'users.id', 'orders.user_id', null, 'o');
$table->bind(BindType::leftJoin, 'order_items', 'o.id', 'order_items.order_id', null, 'oi');
$table->bind(BindType::leftJoin, 'products', 'oi.product_id', 'products.id', null, 'p');

// Złączenie z warunkami AND/OR
$table->bind(
    BindType::leftJoin,
    'orders',
    'users.id',
    'orders.user_id',
    [
        'status' => 'completed',
        'OR' => [
            'total' => ['>', 100],
            'priority' => 'high'
        ]
    ],
    'completed_orders'
);
```

#### Transakcje

[](#transakcje)

```
$transaction = new \krzysztofzylka\DatabaseManager\Transaction();

try {
    $transaction->begin();

    // Operacje bazodanowe
    $table->insert(['name' => 'Product 1']);
    $table->setId(5)->update(['stock' => 10]);

    $transaction->commit();
} catch (\Exception $e) {
    $transaction->rollback();
    echo "Błąd: " . $e->getMessage();
}
```

Schemat bazy danych
-------------------

[](#schemat-bazy-danych)

### Tworzenie tabel

[](#tworzenie-tabel)

```
$createTable = new \krzysztofzylka\DatabaseManager\CreateTable();
$createTable->setName('products');
$createTable->addIdColumn()
    ->addSimpleVarcharColumn('name', 255, false)
    ->addSimpleDecimalColumn('price', '10,2', 0.00)
    ->addSimpleIntColumn('stock', false, true)
    ->addDateCreatedColumn()
    ->addDateModifyColumn();

$createTable->execute();
```

### Modyfikacja struktury tabeli

[](#modyfikacja-struktury-tabeli)

```
$alterTable = new \krzysztofzylka\DatabaseManager\AlterTable('products');

// Dodawanie nowej kolumny
$column = new \krzysztofzylka\DatabaseManager\Column();
$column->setName('description')
    ->setType(\krzysztofzylka\DatabaseManager\Enum\ColumnType::text)
    ->setNull(true);

$alterTable->addColumn($column);

// Modyfikacja typu kolumny
$alterTable->modifyColumn('name', \krzysztofzylka\DatabaseManager\Enum\ColumnType::varchar, 100);

// Usunięcie kolumny
$alterTable->removeColumn('old_column');

$alterTable->execute();
```

Zaawansowane funkcje
--------------------

[](#zaawansowane-funkcje)

### Cache zapytań

[](#cache-zapytań)

```
// Zapisanie danych w cache
\krzysztofzylka\DatabaseManager\Cache::saveData('key', $value);

// Odczytanie danych z cache
$data = \krzysztofzylka\DatabaseManager\Cache::getData('key');
```

### Blokady bazodanowe

[](#blokady-bazodanowe)

```
$lock = new \krzysztofzylka\DatabaseManager\DatabaseLock();

// Zablokowanie zasobu
if ($lock->lock('import_process', 300)) {
    // Wykonaj operację wymagającą wyłącznego dostępu

    // Zwolnienie blokady
    $lock->unlock('import_process');
}
```

Struktura Zwracanych Danych
---------------------------

[](#struktura-zwracanych-danych)

DatabaseManager zwraca dane w ustrukturyzowanym formacie z prefiksem nazwy tabeli. To zapewnia bezpieczeństwo i jasność źródła danych, szczególnie w złożonych zapytaniach z JOIN.

### Pojedynczy Rekord

[](#pojedynczy-rekord)

```
$user = $table->find(['id' => 1]);

// Struktura zwracanych danych:
[
    'users' => [
        'id' => 1,
        'name' => 'Jan Kowalski',
        'email' => 'jan@example.com',
        'age' => 30,
        'date_created' => '2024-01-15 10:30:00'
    ]
]

// Dostęp do danych:
echo $user['users']['name']; // Jan Kowalski
echo $user['users']['email']; // jan@example.com
```

### Wiele Rekordów

[](#wiele-rekordów)

```
$users = $table->findAll();

// Struktura zwracanych danych:
[
    0 => [
        'users' => [
            'id' => 1,
            'name' => 'Jan Kowalski',
            'email' => 'jan@example.com'
        ]
    ],
    1 => [
        'users' => [
            'id' => 2,
            'name' => 'Anna Nowak',
            'email' => 'anna@example.com'
        ]
    ]
]

// Iteracja po danych:
foreach ($users as $user) {
    echo $user['users']['name'] . ' - ' . $user['users']['email'] . "\n";
}
```

### Złączenia (JOIN) z Prefiksami

[](#złączenia-join-z-prefiksami)

```
$table->bind(
    \krzysztofzylka\DatabaseManager\Enum\BindType::leftJoin,
    'orders',
    'users.id',
    'orders.user_id'
);

$usersWithOrders = $table->findAll();

// Struktura zwracanych danych:
[
    0 => [
        'users' => [
            'id' => 1,
            'name' => 'Jan Kowalski',
            'email' => 'jan@example.com'
        ],
        'orders' => [
            'id' => 1,
            'order_number' => 'ORD001',
            'user_id' => 1,
            'total' => 150.00
        ]
    ],
    1 => [
        'users' => [
            'id' => 1,
            'name' => 'Jan Kowalski',
            'email' => 'jan@example.com'
        ],
        'orders' => [
            'id' => 2,
            'order_number' => 'ORD002',
            'user_id' => 1,
            'total' => 75.50
        ]
    ]
]

// Dostęp do danych z różnych tabel:
foreach ($usersWithOrders as $record) {
    echo "Użytkownik: " . $record['users']['name'] . "\n";
    echo "Zamówienie: " . $record['orders']['order_number'] . "\n";
    echo "Kwota: " . $record['orders']['total'] . "\n";
}
```

### Złączenia z Warunkami

[](#złączenia-z-warunkami)

```
$table->bind(
    \krzysztofzylka\DatabaseManager\Enum\BindType::leftJoin,
    'orders',
    'users.id',
    'orders.user_id',
    ['status' => 'completed'] // Warunek w JOIN
);

$completedOrders = $table->findAll();
```

### Praktyczne Wskazówki

[](#praktyczne-wskazówki)

#### 1. Bezpieczny Dostęp do Danych

[](#1-bezpieczny-dostęp-do-danych)

```
// Zawsze sprawdzaj czy klucz istnieje
$user = $table->find(['id' => 1]);

if (isset($user['users']['name'])) {
    echo $user['users']['name'];
} else {
    echo 'Użytkownik nie znaleziony';
}
```

#### 2. Iteracja z Bezpieczeństwem

[](#2-iteracja-z-bezpieczeństwem)

```
$users = $table->findAll();

foreach ($users as $user) {
    $userData = $user['users'] ?? [];
    echo $userData['name'] ?? 'Brak nazwy';
    echo $userData['email'] ?? 'Brak email';
}
```

#### 3. Praca z JOIN

[](#3-praca-z-join)

```
$table->bind(BindType::leftJoin, 'orders', 'users.id', 'orders.user_id');
$results = $table->findAll();

foreach ($results as $record) {
    $userData = $record['users'] ?? [];
    $orderData = $record['orders'] ?? [];

    if (!empty($orderData)) {
        echo "Użytkownik {$userData['name']} ma zamówienie {$orderData['order_number']}\n";
    } else {
        echo "Użytkownik {$userData['name']} nie ma zamówień\n";
    }
}
```

#### 4. Filtrowanie Wyników

[](#4-filtrowanie-wyników)

```
$users = $table->findAll();

// Filtrowanie użytkowników z określonym wiekiem
$adultUsers = array_filter($users, function($user) {
    return ($user['users']['age'] ?? 0) >= 18;
});

// Mapowanie do prostszej struktury
$userNames = array_map(function($user) {
    return $user['users']['name'];
}, $users);
```

### Korzyści Struktury z Prefiksami

[](#korzyści-struktury-z-prefiksami)

1. **Bezpieczeństwo JOIN-ów** - Unika konfliktów nazw kolumn między tabelami
2. **Jasność źródła** - Zawsze wiadomo z której tabeli pochodzą dane
3. **Skalowalność** - Łatwo dodawać kolejne tabele do złączeń
4. **Konsystencja** - Jednolita struktura dla wszystkich zapytań
5. **Debugowanie** - Łatwiejsze śledzenie problemów z danymi

Obsługa błędów
--------------

[](#obsługa-błędów)

Biblioteka wykorzystuje dedykowane klasy wyjątków:

```
try {
    // Kod korzystający z DatabaseManager
} catch (\krzysztofzylka\DatabaseManager\Exception\ConnectException $e) {
    // Błąd połączenia
    echo "Nie można połączyć z bazą danych: " . $e->getHiddenMessage();
} catch (\krzysztofzylka\DatabaseManager\Exception\TransactionException $e) {
    // Błąd transakcji
    echo "Błąd transakcji: " . $e->getHiddenMessage();
} catch (\krzysztofzylka\DatabaseManager\Exception\DatabaseManagerException $e) {
    // Ogólny błąd
    echo "Błąd bazy danych: " . $e->getHiddenMessage();
}
```

Licencja
--------

[](#licencja)

MIT License. Pełna treść w pliku [LICENSE](LICENSE).

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance65

Regular maintenance activity

Popularity22

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~17 days

Recently: every ~9 days

Total

68

Last Release

76d ago

Major Versions

v0.0.3-alpha → v1.0.02022-12-27

### Community

Maintainers

![](https://www.gravatar.com/avatar/b71301619d71d2798d3a84f23de616ac1f1c185ab72e4f03e925cff169b03a0d?d=identicon)[krzysztofzylka](/maintainers/krzysztofzylka)

---

Top Contributors

[![krzysztofzylka](https://avatars.githubusercontent.com/u/41385342?v=4)](https://github.com/krzysztofzylka "krzysztofzylka (166 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/krzysztofzylka-database-manager/health.svg)

```
[![Health](https://phpackages.com/badges/krzysztofzylka-database-manager/health.svg)](https://phpackages.com/packages/krzysztofzylka-database-manager)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90440.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)[wildside/userstamps

Laravel Userstamps provides an Eloquent trait which automatically maintains `created\_by` and `updated\_by` columns on your model, populated by the currently authenticated user in your application.

7511.7M13](/packages/wildside-userstamps)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
