PHPackages                             ywnsyage/clickhouse-php-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. ywnsyage/clickhouse-php-client

ActiveLibrary

ywnsyage/clickhouse-php-client
==============================

Clickhouse client over HTTP and MySQL

3.2.5(4y ago)0291PHPPHP ^7.1|^8.0

Since Jun 7Pushed 4y agoCompare

[ Source](https://github.com/ywnsyage/ClickhouseClient)[ Packagist](https://packagist.org/packages/ywnsyage/clickhouse-php-client)[ RSS](/packages/ywnsyage-clickhouse-php-client/feed)WikiDiscussions master Synced today

READMEChangelog (4)Dependencies (5)Versions (37)Used By (1)

Clickhouse Client
=================

[](#clickhouse-client)

[![Build Status](https://camo.githubusercontent.com/fecc51e99437906a5f878972e92085aa6dbd80a9b72de06430e17bc82d99b5ba/68747470733a2f2f7472617669732d63692e6f72672f7468652d74696e646572626f782f436c69636b686f757365436c69656e742e7376673f6272616e63683d6d617374657226323030)](https://travis-ci.org/the-tinderbox/ClickhouseClient) [![Coverage Status](https://camo.githubusercontent.com/75b6aca6ab83d86d26a0b57ea71e1e454e7590ff066e06dcd8a7693b9c11b2ad/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f7468652d74696e646572626f782f436c69636b686f757365436c69656e742f62616467652e7376673f6272616e63683d6d617374657226323030)](https://coveralls.io/github/the-tinderbox/ClickhouseClient?branch=master)

Package was written as client for [Clickhouse](https://clickhouse.yandex/).

Client uses [Guzzle](https://github.com/guzzle/guzzle) for sending Http requests to Clickhouse servers.

Requirements
------------

[](#requirements)

`php7.1`

Install
-------

[](#install)

Composer

```
composer require ywnsyage/clickhouse-php-client
```

Usage
=====

[](#usage)

Client works with alone server and cluster. Also, client can make async select and insert (from local files) queries.

Alone server
------------

[](#alone-server)

```
$server = new Ywnsyage\Clickhouse\Server('127.0.0.1', '8123', 'default', 'user', 'pass');
$serverProvider = (new Ywnsyage\Clickhouse\ServerProvider())->addServer($server);

$client = new Ywnsyage\Clickhouse\Client($serverProvider);
```

Cluster
-------

[](#cluster)

```
$testCluster = new Ywnsyage\Clickhouse\Cluster('cluster-name', [
    'server-1' => [
        'host' => '127.0.0.1',
        'port' => '8123',
        'database' => 'default',
        'user' => 'user',
        'password' => 'pass'
    ],
    'server-2' => new Ywnsyage\Clickhouse\Server('127.0.0.1', '8124', 'default', 'user', 'pass')
]);

$anotherCluster = new Ywnsyage\Clickhouse\Cluster('cluster-name', [
    [
        'host' => '127.0.0.1',
        'port' => '8125',
        'database' => 'default',
        'user' => 'user',
        'password' => 'pass'
    ],
    new Ywnsyage\Clickhouse\Server('127.0.0.1', '8126', 'default', 'user', 'pass')
]);

$serverProvider = (new Ywnsyage\Clickhouse\ServerProvider())->addCluster($testCluster)->addCluster($anotherCluster);

$client = (new Ywnsyage\Clickhouse\Client($serverProvider));
```

Before execute any query on cluster, you should provide cluster name and client will run all queries on specified cluster.

```
$client->onCluster('test-cluster');

```

By default client will use random server in given list of servers or in specified cluster. If you want to perform request on specified server you should use `using($hostname)` method on client and then run query. Client will remember hostname for next queries:

```
$client->using('server-2')->select('select * from table');
```

Server tags
-----------

[](#server-tags)

```
$firstServerOptionsWithTag = (new \Ywnsyage\Clickhouse\Common\ServerOptions())->setTag('tag');
$secondServerOptionsWithAnotherTag = (new \Ywnsyage\Clickhouse\Common\ServerOptions())->setTag('another-tag');

$server = new Ywnsyage\Clickhouse\Server('127.0.0.1', '8123', 'default', 'user', 'pass', $firstServerOptionsWithTag);

$cluster = new Ywnsyage\Clickhouse\Cluster('cluster', [
    new Ywnsyage\Clickhouse\Server('127.0.0.2', '8123', 'default', 'user', 'pass', $secondServerOptionsWithAnotherTag)
]);

$serverProvider = (new Ywnsyage\Clickhouse\ServerProvider())->addServer($server)->addCluster($cluster);

$client = (new Ywnsyage\Clickhouse\Client($serverProvider));
```

To use server with tag, you should call `usingServerWithTag` function before execute any query.

```
$client->usingServerWithTag('tag');
```

Select queries
--------------

[](#select-queries)

Any SELECT query will return instance of `Result`. This class implements interfaces `\ArrayAccess`, `\Countable` и `\Iterator`, which means that it can be used as an array.

Array with result rows can be obtained via `rows` property

```
$rows = $result->rows;
$rows = $result->getRows();
```

Also you can get some statistic of your query execution:

1. Number of read rows
2. Number of read bytes
3. Time of query execution
4. Rows before limit at least

Statistic can be obtained via `statistic` property

```
$statistic = $result->statistic;
$statistic = $result->getStatistic();

echo $statistic->rows;
echo $statistic->getRows();

echo $statistic->bytes;
echo $statistic->getBytes();

echo $statistic->time;
echo $statistic->getTime();

echo $statistic->rowsBeforeLimitAtLeast;
echo $statistic->getRowsBeforeLimitAtLeast();
```

### Sync

[](#sync)

```
$result = $client->readOne('select number from system.numbers limit 100');

foreach ($result as $number) {
    echo $number['number'].PHP_EOL;
}
```

**Using local files**

You can use local files as temporary tables in Clickhouse. You should pass as third argument array of `TempTable` instances. instance.

In this case will be sent one file to the server from which Clickhouse will extract data to temporary table. Structure of table will be:

- number - UInt64

If you pass such an array as a structure:

```
['UInt64']
```

Then each column from file wil be named as \_1, \_2, \_3.

```
$result = $client->readOne('select number from system.numbers where number in _numbers limit 100', new TempTable('_numbers', 'numbers.csv', [
    'number' => 'UInt64'
]));

foreach ($result as $number) {
    echo $number['number'].PHP_EOL;
}
```

You can provide path to file or pass `FileInterface` instance as second argument.

There is some other types of file streams which could be used to send to server:

- File - simple file stored on disk;
- FileFromString - stream created from string. For example: `new FileFromString('1'.PHP_EOL.'2'.PHP_EOL.'3'.PHP_EOL)`
- MergedFiles - stream which includes many files and merges them all in one. You should pass to constructor file path, which contains list of files which should be megred in one stream.
- TempTable - wrapper to any of `FileInterface` instance and contains structure. Usefull to make inserts using with `MergedFiles`.

### Async

[](#async)

Unlike the `readOne` method, which returns` Result`, the `read` method returns an array of` Result` for each executed query.

```
list($clicks, $visits, $views) = $client->read([
    ['query' => "select * from clicks where date = '2017-01-01'"],
    ['query' => "select * from visits where date = '2017-01-01'"],
    ['query' => "select * from views where date = '2017-01-01'"],
]);

foreach ($clicks as $click) {
    echo $click['date'].PHP_EOL;
}
```

**In `read` method, you can pass the parameter `$concurrency` which is responsible for the maximum simultaneous number of requests.**

**Using local files**

As with synchronous select request you can pass files to the server:

```
list($clicks, $visits, $views) = $client->read([
    ['query' => "select * from clicks where date = '2017-01-01' and userId in _users", new TempTable('_users', 'users.csv', ['number' => 'UInt64'])],
    ['query' => "select * from visits where date = '2017-01-01'"],
    ['query' => "select * from views where date = '2017-01-01'"],
]);

foreach ($clicks as $click) {
    echo $click['date'].PHP_EOL;
}
```

With asynchronous requests you can pass multiple files as with synchronous request.

Insert queries
--------------

[](#insert-queries)

Insert queries always returns true or throws exceptions in case of error.

Data can be written row by row or from local CSV or TSV files.

```
$client->writeOne("insert into table (date, column) values ('2017-01-01',1), ('2017-01-02',2)");
$client->write([
    ['query' => "insert into table (date, column) values ('2017-01-01',1), ('2017-01-02',2)"],
    ['query' => "insert into table (date, column) values ('2017-01-01',1), ('2017-01-02',2)"],
    ['query' => "insert into table (date, column) values ('2017-01-01',1), ('2017-01-02',2)"]
]);

$client->writeFiles('table', ['date', 'column'], [
    new Ywnsyage\Clickhouse\Common\File('/file-1.csv'),
    new Ywnsyage\Clickhouse\Common\File('/file-2.csv')
]);

$client->insertFiles('table', ['date', 'column'], [
    new Ywnsyage\Clickhouse\Common\File('/file-1.tsv'),
    new Ywnsyage\Clickhouse\Common\File('/file-2.tsv')
], Ywnsyage\Clickhouse\Common\Format::TSV);
```

In case of `writeFiles` queries executes asynchronously. If you have butch of files and you want to insert them in one insert query, you can use our `ccat` utility and `MergedFiles` instance instead of `File`. You should put list of files to insert into one file:

```
file-1.tsv
file-2.tsv

```

### Building ccat

[](#building-ccat)

`ccat` sources placed into `utils/ccat` directory. Just run `make && make install` to build and install library into `bin` directory of package. There are already compiled binary of `ccat` in `bin` directory, but it may not work on some systems.

**In `writeFiles` method, you can pass the parameter `$concurrency` which is responsible for the maximum simultaneous number of requests.**

Other queries
-------------

[](#other-queries)

In addition to SELECT and INSERT queries, you can execute other queries :) There is `statement` method for this purposes.

```
$client->writeOne('DROP TABLE table');
```

Testing
-------

[](#testing)

```
$ composer test
```

Roadmap
-------

[](#roadmap)

- Add ability to save query result in local file

Contributing
------------

[](#contributing)

Please send your own pull-requests and make suggestions on how to improve anything. We will be very grateful.

Thx!

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 70.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~51 days

Recently: every ~46 days

Total

33

Last Release

1614d ago

Major Versions

1.4.0 → 2.0.02019-10-03

2.1.0 → 3.0.02020-09-24

PHP version history (2 changes)1.0.0PHP ~7.1

3.1.0PHP ^7.1|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/ce16e09ff46de30a3f837d732dab0e68af514248ac2b5fdd6aa8094cb002e47e?d=identicon)[ywnsyage](/maintainers/ywnsyage)

---

Top Contributors

[![FacedSID](https://avatars.githubusercontent.com/u/11896844?v=4)](https://github.com/FacedSID "FacedSID (26 commits)")[![evsign](https://avatars.githubusercontent.com/u/7965780?v=4)](https://github.com/evsign "evsign (8 commits)")[![rez1dent3](https://avatars.githubusercontent.com/u/5111255?v=4)](https://github.com/rez1dent3 "rez1dent3 (2 commits)")[![romanpravda](https://avatars.githubusercontent.com/u/59819062?v=4)](https://github.com/romanpravda "romanpravda (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ywnsyage-clickhouse-php-client/health.svg)

```
[![Health](https://phpackages.com/badges/ywnsyage-clickhouse-php-client/health.svg)](https://phpackages.com/packages/ywnsyage-clickhouse-php-client)
```

###  Alternatives

[neuron-core/neuron-ai

The PHP Agentic Framework.

1.8k245.3k20](/packages/neuron-core-neuron-ai)[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3731.2M42](/packages/tencentcloud-tencentcloud-sdk-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
