PHP code example of drift / dbal

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

    

drift / dbal example snippets


use Doctrine\DBAL\Platforms\MySqlPlatform;
use Drift\DBAL\Connection;
use Drift\DBAL\Driver\Mysql\MysqlDriver;
use Drift\DBAL\Credentials;
use React\EventLoop\Factory as LoopFactory;

$loop = LoopFactory::create();
$mysqlPlatform = new MySqlPlatform();
$mysqlDriver = new MysqlDriver($loop);
$credentials = new Credentials(
   '127.0.0.1',
   '3306',
   'root',
   'root',
   'test'
);

$connection = Connection::createConnected(
    $mysqlDriver,
    $credentials,
    $mysqlPlatform
);

use Drift\DBAL\Connection;
use Drift\DBAL\Result;

/**
* @var Connection $connection
 */
$promise = $connection
    ->insert('test', [
        'id' => '1',
        'field1' => 'val1',
        'field2' => 'val2',
    ])
    ->then(function(Result $_) use ($connection) {
        $queryBuilder = $connection->createQueryBuilder();
        
        return $connection
            ->query($queryBuilder)
            ->select('*')
            ->from('test', 't')
            ->where($queryBuilder->expr()->orX(
                $queryBuilder->expr()->eq('t.id', '?'),
                $queryBuilder->expr()->eq('t.id', '?')
            ))
            ->setParameters(['1', '2']);
    })
    ->then(function(Result $result) {
        $numberOfRows = $result->fetchCount();
        $firstRow = $result->fetchFirstRow();
        $allRows = $result->fetchAllRows();
    });

$connection->insert('test', [
    'id' => '1',
    'field1' => 'value1'
]);

$connection->update(
    'test',
    ['id' => '1'],
    [
        'field1' => 'value1',
        'field2' => 'value2',
    ]
);

$connection->upsert(
    'test',
    ['id' => '1'],
    [
        'field1' => 'value1',
        'field2' => 'value2',
    ]
);

$connection->delete('test', [
    'id' => '1'
]);

$connection
    ->findOneById('test', [
        'id' => '1'
    ])
    ->then(function(?array $result) {
        if (is_null($result)) {
            // Row with ID=1 not found
        } else {
            // Row with ID=1 found.
            echo $result['id'];
        }   
    });

$connection
    ->findBy('test', [
        'age' => '33'
    ])
    ->then(function(array $result) {
        echo 'Found ' . count($result) . ' rows'; 
    });

$connection->createTable('test', [
    'id' => 'string',
    'name' => 'string',
]);

$schema = new Schema();
$table = $schema->createTable('test');
$table->addColumn('id', 'string');
// ...

$connection->executeSchema($schema);

$connection->dropTable('test');

$connection->truncateTable('test');