Terry
Terry

Reputation: 11

Authenticate and use Google's BigQuery in my php code

I'm setting up my client app using my BigQuery Data, I need to build it with php (which I'm not expert).

I want to authenticate and be able to build queries using php in my server.

I'm having trouble authenticating, as I see different solutions which seem outdated or incomplete.

I've got the JSON key and the project I'd but don't know the proper wait to authenticate to BigQuery.

Can someone tell me how to properly do that? If I need another library (like google cloud auth?)

Upvotes: 0

Views: 992

Answers (1)

Pentium10
Pentium10

Reputation: 207830

Here is the code snippet:

public function getServiceBuilder() {
            putenv('GOOGLE_APPLICATION_CREDENTIALS=path_to_service_account.json');

        $builder = new ServiceBuilder(array(
            'projectId' => PROJECT_ID
        ));

        return $builder;
}

then you can use like this

$builder = $this->getServiceBuilder();
    $bigQuery = $builder->bigQuery();
    $job = $bigQuery->runQueryAsJob('SELECT .......');

    $backoff = new ExponentialBackoff(8);
    $backoff->execute(function () use ($job) {
        $job->reload();
        $this->e('reloading job');
        if (!$job->isComplete()) {
            throw new \Exception();
        }
    });
    if (!$job->isComplete()) {
        $this->e('Job failed to complete within the allotted time.');
        return false;
    }

    $queryResults = $job->queryResults();

    if ($queryResults->isComplete()) {
        $i = 0;
        $rows = $queryResults->rows();

        foreach ($rows as $row) {

(edited)

you may need to add:

use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\ServiceBuilder;
use Google\Cloud\ExponentialBackoff;

and composer.json (this is just an example it may differ the actual version)

{
    "require": {
        "google/cloud": "^0.99.0"
    }
}

Upvotes: 3

Related Questions