PHP code example of smi2 / phpclickhouse

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

    

smi2 / phpclickhouse example snippets


$db = new ClickHouseDB\Client([
    'host'     => '127.0.0.1',
    'port'     => '8123',
    'username' => 'default',
    'password' => '',
]);

$db->database('default');
$db->setTimeout(10);
$db->setConnectTimeOut(5);
$db->ping(true); // throws exception on failure

$statement = $db->select('SELECT * FROM my_table WHERE id = :id', ['id' => 42]);

$statement->rows();      // all rows
$statement->fetchOne();  // first row
$statement->count();     // row count

// Server-side typed binding — SQL injection impossible at protocol level
$result = $db->selectWithParams(
    'SELECT * FROM users WHERE id = {id:UInt32} AND name = {name:String}',
    ['id' => 42, 'name' => 'Alice']
);

$db->insert('my_table',
    [
        [time(), 'key1', 100],
        [time(), 'key2', 200],
    ],
    ['event_time', 'key', 'value']
);

// Memory-efficient — one row at a time, no OOM
foreach ($db->selectGenerator('SELECT * FROM huge_table') as $row) {
    processRow($row);
}

$db->write('CREATE TABLE IF NOT EXISTS my_table (id UInt32, name String) ENGINE = MergeTree ORDER BY id');
$db->write('DROP TABLE IF EXISTS my_table');