PHP code example of yiisoft / data-db

1. Go to this page and download the library: Download yiisoft/data-db library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yiisoft / data-db example snippets


use Yiisoft\Data\Db\QueryDataReader;
use Yiisoft\Data\Reader\Filter\Equals;
use Yiisoft\Data\Reader\Filter\GreaterThan;
use Yiisoft\Data\Reader\Filter\Like;
use Yiisoft\Data\Reader\Filter\AndX;
use Yiisoft\Data\Reader\Sort;
use Yiisoft\Db\Query\Query;

$query = (new Query($db))->from('customer');
$dataReader = new QueryDataReader($query);

// Iterate through results
foreach ($dataReader->read() as $customer) {
    // ... process each customer ...
}

// Read a single record
$customer = $dataReader->readOne();

// Get total count
$total = $dataReader->count();

// Sorting
$sort = Sort::any(['name', 'email'])->withOrderString('-name,email');
$dataReader = $dataReader->withSort($sort);

// Filtering
$filter = new AndX(
    new Equals('status', 'active'),
    new GreaterThan('age', 18),
    new Like('name', 'John')
);
$dataReader = $dataReader->withFilter($filter);

// Pagination
$dataReader = $dataReader
    ->withOffset(20)
    ->withLimit(10);

use Yiisoft\Data\Db\QueryDataReader;
use Yiisoft\Data\Reader\Filter\Equals;

$dataReader = new QueryDataReader(
    query: $query,
    fieldMapper: [
        'userName' => 'user_name',
        'createdAt' => 'created_at',
    ]
);

// Now you can filter and sort by 'userName' and it will use 'user_name' column
$filter = new Equals('userName', 'admin');

use Yiisoft\Data\Db\QueryDataReader;

$dataReader = new QueryDataReader($query);
$dataReader = $dataReader->withBatchSize(100);

foreach ($dataReader->read() as $item) {
    // Items are fetched in batches of 100
}