PHPackages                             kolaykod/simpledb - 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. kolaykod/simpledb

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

kolaykod/simpledb
=================

PHP için özelleştirilmiş PDO sınıfı

0.1(2y ago)0311[2 PRs](https://github.com/KolayKod/simple-db/pulls)MITPHPPHP &gt;=8.0.0

Since Nov 30Pushed 2y ago1 watchersCompare

[ Source](https://github.com/KolayKod/simple-db)[ Packagist](https://packagist.org/packages/kolaykod/simpledb)[ RSS](/packages/kolaykod-simpledb/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)DependenciesVersions (2)Used By (0)

PDB
===

[](#pdb)

PHP için PDO sınıfı

Kurulum ve Kullanım
-------------------

[](#kurulum-ve-kullanım)

```
$ composer require kolaykod/simpledb

```

### Örnek Kullanım

[](#örnek-kullanım)

```
$db = new \kolaykod\simpledb([
    'database' => 'ecommerce',
    'username' => 'root'
    'password' => 'test',
      'prefix' =>'prefix',
    'charset'  => 'utf8'
]);
```

Sqlite kullanımı için:

```
$db = new \kolaykod\simpledb([
    'driver'   => 'sqlite',
    'database' => 'ecommerce.sqlite'
]);
```

### Composer Kullanmadan

[](#composer-kullanmadan)

Yeni bir dizin oluşturarak `src` klasörü altındaki tüm dosyaları içine kopyalayın ve `autoload.php` dosyasını require ile sayfaya dahil ederek sınıfı başlatın.

```
require '{pdb_dosyalarinin_bulundugu_dizin}/autoload.php';

$db = new \kolaykod\simpledb([
    'database' => 'ecommerce',
    'username' => 'root',
    'password' => 'test',
    'charset'  => 'utf8'
]);
```

### Yapılandırma

[](#yapılandırma)

Varsayılan yapılandırma ayarları:

```
[
    'host'      => 'localhost',
    'driver'    => 'mysql',
    'database'  => '',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'debug'     => false,
    'cacheTime' => 60,
    'cachePath' => __DIR__ . '/Cache'
]
```

Şu anda kullanılabilir durumda olan driver listesi:

- Mysql
- Sqlite (test aşamasında)

---

Fetch
-----

[](#fetch)

### Get

[](#get)

Sonuç varsayılan olarak `Object` formatında döner. `Array` olarak ulaşmak isterseniz `toArray()` metoduna göz atın.

```
$products = $db->get('products');

foreach ($products as $product) {
    echo $product->name;
}
```

- `get()`
- `get('products')`

---

Kullanılabilecek metodlar: `get()`, `first()`, `value()`, `pluck()`, `find()`

```
$products = $db->select('id, name, code, slug, price, stock')
               ->table('products')
               ->where('stock > ?', 5)
               ->where('MONTH(created) = MONTH(NOW())')
               ->order('id')
               ->get();
```

Yukarıdaki zincirin sorgu çıktısı şu şekilde olacaktır:

```
SELECT
  id, name, code, slug, price, stock
FROM
  products
WHERE
  stock > ?
  AND MONTH(created) = MONTH(NOW())
ORDER BY
  id DESC
```

### toArray()

[](#toarray)

Sonuçlara `Array` formatında ulaşmak için kullanılır.

```
$products = $db->table('products')
               ->toArray()
               ->get();

foreach ($products as $product) {
    echo $product['name'];
}
```

### toJson()

[](#tojson)

Sonuçlara `Json` formatında ulaşmak için kullanılır.

```
$products = $db->table('products')
               ->toJson()
               ->get();
```

### First

[](#first)

Bir tablodan sadece tek bir satır almanız gerekiyorsa, `first()` yöntemini kullanabilirsiniz. Bu yöntem, varsayılan olarak tek bir stdClass nesnesi döndürür.

```
$user = $db->table('users')
           ->first();

echo $user->email;
```

### Value

[](#value)

Bir satırın tamamına ihtiyacınız yoksa, value yöntemini kullanarak bir kayıttan tek bir değer çıkarabilirsiniz.

```
$email = $db->table('users')
            ->where('name', 'Walter')
            ->value('email');

echo $email;
```

### Pluck

[](#pluck)

Tek bir sütunun değerlerini içeren bir dizi istiyorsanız `pluck()` yöntemini kullanabilirsiniz.

```
$pluck = $db->table('products')
            ->pluck('name');
```

```
Array
(
    [0] => Apple Iphone X 128 GB
    [1] => Apple Iphone X 256 GB
    [2] => Apple Iphone X 512 GB
)

```

`pluck()` metoduna ikinci bir parametre göndererek, elde edilen dizinin anahtarları olarak kullanılmasını istediğiniz sütunu belirtebilirsiniz:

```
$pluck = $db->table('products')
            ->pluck('name', 'code');
```

```
Array
(
    [APPLEX128] => Apple Iphone X 128 GB
    [APPLEX256] => Apple Iphone X 256 GB
    [APPLEX512] => Apple Iphone X 512 GB
)

```

### Find

[](#find)

Birincil anahtarla eşleşen kaydı döndürür.

```
$user = $db->table('users')
           ->find(15);
```

```
SELECT * FROM users WHERE id=?
```

- `find(15)`
- `find(15, 'products')`

### Total

[](#total)

Toplam satır sayısına ulaşmak için kullanılır.

```
$total = $db->table('users')
            ->where('userGroup', 'Admin')
            ->total();
```

- `total()`
- `total('users')`

### rowCount()

[](#rowcount)

Etkilenen satır sayısı veya okunan satır sayısına ulaşmak için kullanılır.

```
echo $db->rowCount();
```

### lastInsertId()

[](#lastinsertid)

Insert işlemlerinde kaydedilen son satırın birincil anahtarını döndürür.

```
echo $db->lastInsertId();
```

---

Raw Query
---------

[](#raw-query)

Salt sql sorgusu çalıştırmak için kullanılır.

### Raw Fecth

[](#raw-fecth)

```
$results = $db->raw('SELECT id FROM products WHERE active = ? AND MONTH(created) = MONTH(NOW())', 1)
              ->getCols();
```

### Raw Exec

[](#raw-exec)

```
$update = $db->raw('UPDATE payments SET active = !active WHERE status = ?', ['paid'])
             ->exec();
```

---

Pager
-----

[](#pager)

Parametre olarak sayfa başına listelenecek kayıt sayısı gönderilmelidir. `pager()` metodu salt sorgularda çalışmaz.

```
$posts = $db->table('posts')
            ->pager(25)
            ->get();
```

`pager()` fonksiyonu 2 parametre alır. İlk parametre sayfa başına listelenecek kayıt sayısı, İkinci parametre sayfa bilgisinin aktarılacağı `$_GET` parametresidir. Örneğin link yapısı `?sayfa=3` şeklinde kurgulanacaksa, örnek kullanım şu şekilde olmalıdır;

```
$db->pager(25, 'sayfa');
```

### pagerLinks()

[](#pagerlinks)

Linklerin çıktısını almak için kullanılır.

```
echo $db->pagerLinks();
```

- `«` `‹` `1` `2` `3` `4` `5` `6` `...` `›` `»`

### pagerData()

[](#pagerdata)

Toplam sonuç, sayfa sayısı, limit, ofset ve aktif sayfa gibi bilgilere ulaşmak için kullanılır.

```
var_dump($db->pagerData());
```

```
Array
(
    [count] => 255
    [limit] => 10
    [offset] => 0
    [total] => 26
    [current] => 1
)

```

### setPagerTemplate()

[](#setpagertemplate)

Link çıktısına ait HTML şablonu düzenlemek için kullanılır.

```
$db->setPagerTemplate('

            {text}

    ');
```

---

Cache
-----

[](#cache)

Sonuçları önbelleğe almak için kullanılır. Çok sık değişmesi gerekmeyen ve yoğun kullanımda performans sorunu oluşturabilecek sorgular için kullanılabilir.

### Disk Cache

[](#disk-cache)

`comments` tablosundaki verileri mysql'den okur ve diske kaydeder. Sonuçlar 30 saniye boyunca diskten okunur.

```
$results = $db->cache(30)->get('comments');
```

`fromDisk()` metodu; son sorgu diskten okunuyorsa `true`, mysql'den okunuyorsa `false` döner.

### Redis Cache

[](#redis-cache)

`comments` tablosundaki verileri mysql'den okur ve redis veritabanına kayder. Sonuçlar 30 saniye boyunca Redis üzerinden okunur.

```
$results = $db->redis(30)->get('comments');
```

`fromRedis()` metodu; son sorgu Redisten okunuyorsa `true`, mysql'den okunuyorsa `false` döner.

```
$redisConnect = (function(){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379, 1, NULL, 0, 0, ['auth' => ['default', '']]);
    return $redis;
});

$db->setRedis($redisConnect());
```

`setRedis()` metodu ile Redis sınıfı dışarıdan dahil edilebilir.

> Not: Redis ile önbellekleme işlemi yapabilmek için sunucunuzda Redis yüklü olması gerekir.

---

Insert
------

[](#insert)

Tabloya yeni bir satır eklemek için kullanılır. `insert()` metoduyla tek veya birden fazla kayıt eklenebilir.

### Tekli Kayıt

[](#tekli-kayıt)

```
$db->table('products')->insert([
    'name'  => 'Apple Iphone X 128 Gb',
    'code'  => 'APPLEX128',
    'price' => '999.9'
]);
```

### Çoklu Kayıt

[](#çoklu-kayıt)

```
$db->table('products')->insert([
    ['name' => 'Apple Iphone X 128 Gb', 'code' => 'APPLEX128', 'price' => '999.9'],
    ['name' => 'Apple Iphone X 256 Gb', 'code' => 'APPLEX256', 'price' => '1149.9'],
    ['name' => 'Apple Iphone X 512 Gb', 'code' => 'APPLEX512', 'price' => '1349.9']
]);
```

Son kaydedilen satırın birincil anahtarına ulaşmak için `lastInsertId()` metodunu, toplam etkilenen satır sayısı için `rowCount()` metodunu kullanabilirsiniz.

### Upsert

[](#upsert)

```
$db->table('products')->upsert([
    'name'  => 'Apple Iphone X 128 Gb',
    'code'  => 'APPLEX128',
    'price' => '999.9'
]);
```

Benzersiz anahtarlara eşleşen veri bulunursa var olan kayıt güncellenir, yoksa yeni kayıt eklenir.

- Henüz Sqlite desteği yok.

### Insert Ignore

[](#insert-ignore)

```
$db->table('products')->insertIgnore([
    'name'  => 'Apple Iphone X 128 Gb',
    'code'  => 'APPLEX128',
    'price' => '999.9'
]);
```

Benzersiz anahtarlara eşleşen veri bulunursa kayıt eklenmez, yoksa yeni kayıt eklenir.

### Insert Replace

[](#insert-replace)

```
$db->table('products')->insertReplace([
    'name'  => 'Apple Iphone X 128 Gb',
    'code'  => 'APPLEX128',
    'price' => '999.9'
]);
```

Benzersiz anahtarlara eşleşen veri bulunursa var olan kayıt silinir ve yeni kayıt eklenir, yoksa yeni kayıt eklenir. Her replace işleminde `auto_increment` olarak tanımlanan birincil anahtara (Genellikle ID) ait değer değişir. Değerin korunmasını istiyorsanız `upsert()` metodunu kullanmanız önerilir.

---

Update
------

[](#update)

Bir veya birden fazla kaydı güncellemek için kullanılır.

```
$update = $db->table('products')
             ->where('id', 11255)
             ->update(['active' => 1]);
```

- Etkilenen satır sayısı döner.

### Touch

[](#touch)

`active` sütunu `1` ise `0`, `0` ise `1` değerini alır.

```
$touch = $db->table('products')
            ->touch('active');
```

- `touch('active', 'products')`

### Increment

[](#increment)

`hit` sütunu `1` veya gönderilen değer kadar artar.

```
$increment = $db->table('posts')
                ->where('slug', 'whats-new-in-laravel-8')
                ->increment('hit');
```

- `increment('hit')`
- `increment('hit', 5)`

### Decrement

[](#decrement)

`hit` sütunu `1` veya gönderilen değer kadar azalır.

```
$increment = $db->table('posts')
                ->where('slug', 'whats-new-in-laravel-8')
                ->decrement('hit');
```

- `decrement('hit')`
- `decrement('hit', 5)`

---

Delete
------

[](#delete)

Bir veya birden fazla kaydı silmek için kullanılır.

```
$delete = $db->in('id', [321, 412, 324, 142])
             ->delete('products');
```

- Etkilenen satır sayısı döner.

---

Filter
------

[](#filter)

Gönderilen veriyi tablodaki sütunlarla karşılaştırır ve yanlış/fazla veriyi otomatik olarak temizler. `insert()`, `insertIgnore()`, `insertReplace()`, `upsert()`, `update()` metodlarıyla birlikte kullanılabilir.

PrimaryNot NullNot NullNot Nullenum('Male', 'Female')idnameemailpasswordgender`users` adında bir tablomuz olduğunu ve yukarıdaki sütunlardan oluştuğunu varsayalım.

```
$db->table('users')->filter()->insert([
    'username' => 'walterbishop',
    'email'    => 'walter@bishop.com',
    'password' => 'U7!hsjlIus',
    'gender'   => 'Male',
    'fullname' => 'Walter Bishop'
]);
```

- `filter()` metodu users tablosunda `fullname` sütununu bulamadığı için bu veriyi otomatik temizleyip hatasız bir şekilde kayıt oluşturulmasını sağlar.

```
$db->table('users')->filter()->insert($_POST);
```

- `$_POST` ile gönderilen formlar için örnek bir kullanım şekli.

Validate
--------

[](#validate)

Bu metot şu an için yalnızca; gönderilen veriyi filtreler, boş gönderilen alanları varsayılan değerleriyle doldurur, not null ve enum kontrolleri yapar.

```
try{
    $db->table('users')->validate()->insert([
        'username' => 'walterbishop',
        'email'    => 'walter@bishop.com',
        'password' => 'U7!hsjlIus',
        'gender'   => 'Elephant'
    ]);
} catch(Exception $e){
    echo $e->getMessage();
}
```

- `gender` sütununda tanımlı enum değerleri arasında `Elephant` olmadığı için hata döner ve kayıt eklenmez.

---

Transaction
-----------

[](#transaction)

Metodlar: `inTransaction()`, `beginTransaction()`, `commit()`, `rollBack()`

```
try {

    $db->beginTransaction();

    $db->table('products')->insert([
        'name'  => 'Apple Iphone X 128 Gb',
        'code'  => 'APPLEX128',
        'price' => '999.9'
    ]);

    $db->table('images')->insert([
        'productId' => $db->lastInsertId(),
        'imageName' => 'foo.jpg'
    ]);

    $db->commit();

} catch(Exception $e) {

    $db->rollBack();
}
```

---

Select
------

[](#select)

```
$db->select('id, name, code, price')...
```

- `select('id, name')`
- `select(['id', 'name', ...])`

> Metod kullanılmazsa varsayılan olarak `*` ile tüm sütunlar seçilir.

### Select Functions

[](#select-functions)

Metodlar: `count()`, `sum()`, `avg()`, `min()`, `max()`

```
$db->sum('amount')...
```

- `sum('amount')`
- `sum('amount', 'totalAmount')`

Table
-----

[](#table)

`table()` ve `from()` metodu aynı işlevi görür.

```
$db->table('products')...
```

- `table('products')`
- `table(['products as p', 'images as i'])`

Join
----

[](#join)

Metodlar: `leftJoin()`, `rightJoin()`, `innerJoin()`, `leftOuterJoin()`, `rightOuterJoin()`, `fullOuterJoin()`

```
$db->table('products as p')
   ->leftJoin('images as i', 'p.id', 'i.productId')
   ->get();
```

- `leftJoin('images', 'products.id', 'images.productId')`
- `leftJoin('images', 'products.id = images.productId')`
- `leftJoin('images ON products.id = images.productId')`

Where
-----

[](#where)

Metodlar: `where()`, `orWhere()`, `notWhere()`, `orNotWhere()`

```
$db->where('id', 32886)...
```

- `where('active', 1)`
- `where('stock >= ? AND active = ?', [2, 1])`
- `where(['stock > ?', 'active > ?'], [2, 1])`
- `where(['stock' => 2, 'active' => 1])`
- `where('stock >= 2 AND active = 1 AND MONTH(updated) = MONTH(NOW())')`

Group Where
-----------

[](#group-where)

```
$db->table('products')
   ->like('name', '%iphone%')
   ->grouped(function($q){
        $q->in('brandId', [1, 2, 3])->orIn('categoryId', [1, 2, 3]);
   })->get();
```

- `SELECT * FROM products WHERE name LIKE ? AND (brandId IN(?,?,?) OR categoryId IN(?,?,?))`

Between
-------

[](#between)

Metodlar: `between()`, `orBetween()`, `notBetween()`, `orNotBetween()`

```
$db->between('price', 50, 250)...
```

Is Null - Not Null
------------------

[](#is-null---not-null)

Metodlar: `isNull()`, `orIsNull()`, `notNull()`, `orNotNull()`

```
$db->isNull('code')...
```

- `isNull('slug')`
- `isNull(['slug', ...])`

In - Not In
-----------

[](#in---not-in)

Metodlar: `in()`, `orIn()`, `notIn()`, `orNotIn()`

```
$db->in('id', [33922, 31221, 45344, 35444])...
```

Find In Set
-----------

[](#find-in-set)

Metodlar: `findInSet()`, `orFindInSet()`, `notFindInSet()`, `orNotFindInSet()`

```
$db->findInSet('categoryId', 139)...
```

Like - Not Like
---------------

[](#like---not-like)

Metodlar: `like()`, `orLike()`, `notLike()`, `orNotlike()`

```
$db->like('name', '%Apple%')...
```

Order
-----

[](#order)

Varsayılan olarak `desc` seçilir.

```
$db->order('id')...
```

- `order('id')`
- `order('id', 'asc')`
- `order('id desc, name asc')`
- `order('rand()')`

Group
-----

[](#group)

```
$db->group('id')...
```

- `group('id')`
- `group(['id', 'name'])`

Having
------

[](#having)

```
$db->having('stock', 5)...
```

- `having('stock', 5)`
- `having('stock > 5')`
- `having('stock > ?', 5)`

Limit - Offset
--------------

[](#limit---offset)

Limit, Offset ve Sayfalama işlemleri için kullanılır.

```
$db->limit(100)...
$db->limit(100, 0)...
$db->limit(100)->offset(0)...
```

History
-------

[](#history)

### queryHistory()

[](#queryhistory)

Sorgu listesine ulaşmak için kullanılır.

```
var_dump($db->queryHistory());
```

```
Array
(
    [0] => Array
        (
            [query] => SELECT id, name FROM products WHERE code = ? AND active = ? ORDER BY id desc
            [params] => Array
                (
                    [0] => 34066
                    [1] => 1
                )

            [from] => redis
        )
)

```

### lastQuery()

[](#lastquery)

Son sorguyu görüntülemek için kullanılır.

```
echo $db->lastQuery();
```

- `SELECT id, name FROM products WHERE code = ? AND active = ? ORDER BY id desc`

### lastParams()

[](#lastparams)

Son sorguyu ait parametreleri görmek için kullanılır.

```
var_dump($db->lastParams());
```

```
Array
(
    [0] => 34066,
    [1] => 1
)

```

### queryCount()

[](#querycount)

Toplam sorgu sayısına ulaşmak için kullanılır.

```
echo $db->queryCount();
```

- `1`

---

Structure
---------

[](#structure)

Yapısal sorgular için kullanılır.

```
$db->repair('sessions');
```

Metodlar: `truncate()`, `drop()`, `optimize()`, `analyze()`, `check()`, `checksum()`, `repair()`

Contributors
------------

[](#contributors)

- [kolaykod](https://github.com/kolaykod) kolaykod

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 93.9% 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

Unknown

Total

1

Last Release

891d ago

### Community

Maintainers

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

---

Top Contributors

[![proff56](https://avatars.githubusercontent.com/u/5316163?v=4)](https://github.com/proff56 "proff56 (31 commits)")[![hakanz](https://avatars.githubusercontent.com/u/11519888?v=4)](https://github.com/hakanz "hakanz (2 commits)")

---

Tags

phpdatabasepdorediscacheveritabani

### Embed Badge

![Health badge](/badges/kolaykod-simpledb/health.svg)

```
[![Health](https://phpackages.com/badges/kolaykod-simpledb/health.svg)](https://phpackages.com/packages/kolaykod-simpledb)
```

###  Alternatives

[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[clouddueling/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k22.9k](/packages/clouddueling-mysqldump-php)

PHPackages © 2026

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