You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从PHP Web应用向CosmosDB(SQL API)插入文档?能否执行插入查询?

Inserting Documents into Cosmos DB (SQL API) from a PHP Web App + Insert Query Support

Hey there! Great question. Let's cover both how to insert documents into Cosmos DB (SQL API) using PHP, and whether you can use insert queries—spoiler: you absolutely can.

First: Yes, You Can Use Insert Queries

Cosmos DB's SQL API supports standard SQL-like INSERT statements to add documents directly via query. We'll cover that alongside the SDK's native insert method below.

Step 1: Set Up the Azure Cosmos DB PHP SDK

First, you'll need to install the official SDK via Composer. Run this command in your project directory:

composer require microsoft/azure-cosmos

Step 2: Insert Documents (Two Methods)

Method 1: Use the SDK's Native createItem() Method

This is the recommended approach for most cases, as it handles things like partitioning and error handling out of the box. Here's a complete example:

<?php
require 'vendor/autoload.php';

use Microsoft\Azure\Cosmos\CosmosClient;
use Microsoft\Azure\Cosmos\Exception\CosmosException;

// Replace these with your Cosmos DB credentials
$endpoint = 'YOUR_COSMOS_DB_ENDPOINT';
$key = 'YOUR_COSMOS_DB_PRIMARY_KEY';
$databaseName = 'YourDatabaseName';
$containerName = 'YourContainerName';

try {
    // Initialize the Cosmos client
    $client = new CosmosClient($endpoint, $key);

    // Get references to your database and container
    $database = $client->getDatabase($databaseName);
    $container = $database->getContainer($containerName);

    // Define your document (must include an "id" field, plus any other properties)
    $document = [
        'id' => uniqid('user_'), // Unique ID for the document
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'age' => 30,
        'isActive' => true
    ];

    // Insert the document
    $response = $container->createItem($document);

    echo "Document inserted successfully! Document ID: " . $response->getResource()['id'];
} catch (CosmosException $e) {
    echo "Error inserting document: " . $e->getMessage();
}
?>

Method 2: Execute an INSERT Query

If you prefer using SQL syntax, you can run an INSERT query directly. Here's how:

<?php
require 'vendor/autoload.php';

use Microsoft\Azure\Cosmos\CosmosClient;
use Microsoft\Azure\Cosmos\Exception\CosmosException;

$endpoint = 'YOUR_COSMOS_DB_ENDPOINT';
$key = 'YOUR_COSMOS_DB_PRIMARY_KEY';
$databaseName = 'YourDatabaseName';
$containerName = 'YourContainerName';

try {
    $client = new CosmosClient($endpoint, $key);
    $database = $client->getDatabase($databaseName);
    $container = $database->getContainer($containerName);

    // Define your INSERT SQL query
    $query = "INSERT INTO YourContainerName (id, name, email, age, isActive) 
              VALUES ('user_" . uniqid() . "', 'Jane Smith', 'jane@example.com', 28, true)";

    // Execute the query
    $resultSet = $container->executeQuery($query);

    // Check if the insert was successful
    $response = $resultSet->getResponse();
    if ($response->getStatusCode() === 200) {
        echo "Document inserted via query successfully!";
    } else {
        echo "Query execution returned unexpected status code: " . $response->getStatusCode();
    }
} catch (CosmosException $e) {
    echo "Error executing insert query: " . $e->getMessage();
}
?>

Key Notes to Remember

  • Required id Field: Every document must have a unique id field (case-sensitive). You can generate it manually or let Cosmos DB auto-generate it (but auto-generated IDs are longer strings).
  • Partition Keys: If your container uses a partition key, make sure your document includes that field—otherwise, the insert will fail.
  • Error Handling: Always wrap operations in try/catch blocks to handle common issues like duplicate IDs, missing partition keys, or connection problems.
  • Performance: The createItem() method is generally more efficient for single inserts, while queries are useful if you need to batch inserts (though for large volumes, consider the bulk executor library).

内容的提问来源于stack exchange,提问作者Khin Thet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:40:44