要高效地使用PHP連接InfluxDB數(shù)據(jù)庫,建議使用InfluxDB的官方客戶端庫。在PHP中,你可以使用influxdb-php
庫。首先,確保你已經(jīng)通過Composer安裝了該庫:
composer require influxdb/influxdb-php
然后,你可以按照以下示例代碼高效地連接到InfluxDB數(shù)據(jù)庫:
<?php
require_once 'vendor/autoload.php';
use InfluxDB\Client;
use InfluxDB\Point;
use InfluxDB\WriteOptions;
// InfluxDB連接配置
$host = 'http://localhost:8086'; // 默認(rèn)InfluxDB端口為8086
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';
// 創(chuàng)建InfluxDB客戶端實(shí)例
$client = new Client($host, $username, $password);
// 選擇要操作的數(shù)據(jù)庫
$client->selectDatabase($database);
// 創(chuàng)建寫入選項(xiàng)實(shí)例
$writeOptions = new WriteOptions();
// 創(chuàng)建一個Point實(shí)例,并設(shè)置相關(guān)屬性
$point = new Point(
'your_measurement', // measurement名稱
[
'field1' => 123, // 字段名和字段值
'field2' => 456,
],
[
'time' => '2022-01-01T00:00:00Z', // 時間戳
],
$writeOptions
);
// 將Point寫入InfluxDB
$client->writePoints([$point]);
// 查詢數(shù)據(jù)
$query = 'SELECT * FROM "your_measurement" WHERE time > now() - 1h';
$result = $client->query($query);
// 處理查詢結(jié)果
foreach ($result as $row) {
print_r($row);
}
// 關(guān)閉客戶端連接
$client->close();
請確保將示例代碼中的your_username
、your_password
、your_database
、your_measurement
等占位符替換為實(shí)際的值。此外,你可以根據(jù)需要調(diào)整查詢條件和時間范圍。