1. Go to this page and download the library: Download enginema/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/ */
enginema / phpclickhouse example snippets
// vendor autoload
$db = new ClickHouseDB\Client(['config_array']);
$db->ping();
$statement = $db->select('SELECT * FROM summing_url_views LIMIT 2');
// Count select rows
$statement->count();
// Count all rows
$statement->countAll();
// fetch one row
$statement->fetchOne();
// get extremes min
print_r($statement->extremesMin());
// totals row
print_r($statement->totals());
// result all
print_r($statement->rows());
// totalTimeRequest
print_r($statement->totalTimeRequest());
// raw answer JsonDecode array, for economy memory
print_r($statement->rawData());
// raw curl_info answer
print_r($statement->responseInfo());
// human size info
print_r($statement->info());
// if clickhouse-server version >= 54011
$db->settings()->set('output_format_write_statistics',true);
print_r($statement->statistics());
$db->write('DROP TABLE IF EXISTS summing_url_views');
$state1 = $db->selectAsync('SELECT 1 as ping');
$state2 = $db->selectAsync('SELECT 2 as ping');
// run
$db->executeAsync();
// result
print_r($state1->rows());
print_r($state2->fetchOne('ping'));
$select = $db->selectAsync('SELECT * FROM summing_url_views LIMIT 1');
$insert = $db->insertBatchFiles('summing_url_views', ['/tmp/clickHouseDB_test.1.data'], ['event_time']);
// 'Exception' with message 'Queue must be empty, before insertBatch, need executeAsync'
$WriteToFile=new ClickHouseDB\WriteToFile('/tmp/_1_select.csv');
$db->select('select * from summing_url_views',[],null,$WriteToFile);
// or
$db->selectAsync('select * from summing_url_views limit 4',[],null,new ClickHouseDB\WriteToFile('/tmp/_3_select.tab',true,'TabSeparatedWithNames'));
$db->selectAsync('select * from summing_url_views limit 4',[],null,new ClickHouseDB\WriteToFile('/tmp/_4_select.tab',true,'TabSeparated'));
$statement=$db->selectAsync('select * from summing_url_views limit 54',[],null,new ClickHouseDB\WriteToFile('/tmp/_5_select.csv',true,ClickHouseDB\WriteToFile::FORMAT_CSV));
$streamWrite=new ClickHouseDB\Transport\StreamWrite($stream);
$client->streamWrite(
$streamWrite, // StreamWrite Class
'INSERT INTO {table_name} FORMAT JSONEachRow', // SQL Query
['table_name'=>'_phpCh_SteamTest'] // Binds
);
$stream = fopen('php://memory','r+');
for($f=0;$f<23;$f++) { // Make json data in stream
fwrite($stream, json_encode(['a'=>$f]).PHP_EOL );
}
rewind($stream); // rewind stream
$streamWrite=new ClickHouseDB\Transport\StreamWrite($stream);
$streamWrite->applyGzip(); // Add Gzip zlib.deflate in stream
$callable = function ($ch, $fd, $length) use ($stream) {
return ($line = fread($stream, $length)) ? $line : '';
};
// Apply closure
$streamWrite->closure($callable);
// Run Query
$r=$client->streamWrite($streamWrite,'INSERT INTO {table_name} FORMAT JSONEachRow', ['table_name'=>'_phpCh_SteamTest']);
// Result
print_r($r->info_upload());
$stream = fopen('php://memory','r+');
$streamRead=new ClickHouseDB\Transport\StreamRead($stream);
$r=$client->streamRead($streamRead,'SELECT sin(number) as sin,cos(number) as cos FROM {table_name} LIMIT 4 FORMAT JSONEachRow', ['table_name'=>'system.numbers']);
rewind($stream);
while (($buffer = fgets($stream, 4096)) !== false) {
echo ">>> ".$buffer;
}
fclose($stream); // Need Close Stream
// Send to closure
$stream = fopen('php://memory','r+');
$streamRead=new ClickHouseDB\Transport\StreamRead($stream);
$callable = function ($ch, $string) use ($stream) {
// some magic for _BLOCK_ data
fwrite($stream, str_ireplace('"sin"','"max"',$string));
return strlen($string);
};
$streamRead->closure($callable);
$r=$client->streamRead($streamRead,'SELECT sin(number) as sin,cos(number) as cos FROM {table_name} LIMIT 44 FORMAT JSONEachRow', ['table_name'=>'system.numbers']);
$config = [
'host' => 'cluster.clickhouse.dns.com', // any node name in cluster
'port' => '8123',
'sslCA' => '...',
];
$config = [
'host' => 'cluster.clickhouse.dns.com', // any node name in cluster
'port' => '8123',
'username' => 'default', // all node have one login+password
'password' => ''
];
// client connect first node, by DNS, read list IP, then connect to ALL nodes for check is !OK!
$cl = new ClickHouseDB\Cluster($config);
$cl->setScanTimeOut(2.5); // 2500 ms, max time connect per one node
// Check replica state is OK
if (!$cl->isReplicasIsOk())
{
throw new Exception('Replica state is bad , error='.$cl->getError());
}
// get array nodes, and clusers
print_r($cl->getNodes());
print_r($cl->getClusterList());
// get node by cluster
$name='some_cluster_name';
print_r($cl->getClusterNodes($name));
// get counts
echo "> Count Shard = ".$cl->getClusterCountShard($name)."\n";
echo "> Count Replica = ".$cl->getClusterCountReplica($name)."\n";
// get nodes by table & print size per node
$nodes=$cl->getNodesByTable('shara.adpreview_body_views_sharded');
foreach ($nodes as $node)
{
echo "$node > \n";
// select one node
print_r($cl->client($node)->tableSize('adpreview_body_views_sharded'));
print_r($cl->client($node)->showCreateTable('shara.adpreview_body_views'));
}
// work with one node
// select by IP like "*.248*" = `123.123.123.248`, dilitmer `;` , if not fount -- select first node
$cli=$cl->clientLike($name,'.298;.964'); // first find .298 then .964 , result is ClickHouseDB\Client
$cli->ping();
// truncate table on cluster
$result=$cl->truncateTable('dbNane.TableName_sharded');
// get one active node ( random )
$cl->activeClient()->setTimeout(0.01);
$cl->activeClient()->write("DROP TABLE IF EXISTS default.asdasdasd ON CLUSTER cluster2");
// find `is_leader` node
$cl->getMasterNodeForTable('dbNane.TableName_sharded');
// errors
var_dump($cl->getError());
//
$db->enableExtremes(true);
$db->enableLogQueries();
$db->select('SELECT 1 as p');
print_r($db->select('SELECT * FROM system.query_log')->rows());