PHP code example of ksfraser / ksf-common-db

1. Go to this page and download the library: Download ksfraser/ksf-common-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/ */

    

ksfraser / ksf-common-db example snippets


// Inside FA (runtime):
$db = new \ksfraser\CommonDb\Adapter\FaDbAdapter(TB_PREF);

// Standalone / tests / CLI:
$pdo = new PDO('mysql:host=...;dbname=...');
$db  = new \ksfraser\CommonDb\Adapter\PdoDbAdapter($pdo);
// or in-memory SQLite:
$db  = new \ksfraser\CommonDb\Adapter\PdoDbAdapter(new PDO('sqlite::memory:'));

use ksfraser\CommonDb\Dictionary\TableDefinition;
use ksfraser\CommonDb\Query\QueryBuilder;

// Data dictionary drives schema + CRUD SQL (unprefixed logical name; the FA
// adapter prefixes the physical table at runtime).
$def = (new TableDefinition('product_attribute_assignments', 'id'))
    ->column('id', 'int(11)', 'NOT NULL', true)
    ->column('stock_id', 'varchar(32)', 'NOT NULL')
    ->column('category_id', 'int(11)', 'NOT NULL')
    ->index('uq_stock_cat', 'unique', 'stock_id, category_id');

$db->executeUpdate($def->createSql());                  // CREATE TABLE IF NOT EXISTS
$db->executeUpdate($def->insertSql(), ['stock_id' => 'P-1', 'category_id' => 3]);

$qb = (new QueryBuilder())
    ->select('stock_id')
    ->from('product_attribute_assignments')
    ->where('category_id = :cat', ['cat' => 3]);

$rows = $db->fetchAll($qb->toSql(), $qb->getParams());  // or $qb->fetch($db)