Menu
Amazon DynamoDB
Developer Guide (API Version 2012-08-10)

Working with Items: PHP

You can use AWS SDK for PHP to perform typical create, read, update, and delete (CRUD) operations on an item in a table. The SDK operations map to the underlying low-level actions in DynamoDB. For more information, see PHP Code Samples.

The following are the common steps that you follow to perform data CRUD operations using the AWS SDK for PHP.

  1. Create an instance of the DynamoDB client.

  2. Provide the parameters for a DynamoDB operation, including any optional parameters.

  3. Load the response from DynamoDB into a local variable for your application.

Putting an Item

The PHP putItem function uploads an item to a table. If the item exists, it replaces the entire item. Instead of replacing the entire item, if you want to update only specific attributes, you can use the updateItem function. For more information, see Updating an Item.

The following PHP code snippet demonstrates the preceding tasks. The code uploads an item to the ProductCatalog table.

Note

This code sample assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Creating Tables and Loading Sample Data section. Alternatively, you can load the data using the instructions in the Creating Example Tables and Uploading Data Using the AWS SDK for PHP topic.

For step-by-step instructions to run the following example, see PHP Code Samples.


require 'vendor/autoload.php';

$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest'
]);

$dynamodb = $sdk->createDynamoDb();

$response = $dynamodb->putItem([
    'TableName' => 'ProductCatalog',
    'Item' => [
        'Id'       => ['N'      => '104'      ], // Primary Key
        'Title'    => ['S'      => 'Book 104 Title' ],
        'ISBN'     => ['S'      => '111-1111111111' ],
        'Price'    => ['N'      => '25' ],
        'Authors'  => ['SS'  => ['Author1', 'Author2'] ]
                ]
]);

print_r($response);

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters to the putItem function. For example, the following PHP code snippet uses an optional parameter to specify a condition for uploading the item. If the condition you specify is not met, then the AWS PHP SDK throws an ConditionalCheckFailedException. The code specifies the following optional parameters in for putItem:

  • A ConditionExpression parameter that define conditions for the request, such as the condition that the existing item is replaced only if it has an ISBN attribute that equals a specific value.

  • The ALL_OLD value for the ReturnValue parameter that provides all the attribute values for the item before the PutItem operation. In this case, the older item only had two authors and the new item values include three authors.


$tableName = 'ProductCatalog';

$result = $dynamodb->putItem ([
    'TableName' => $tableName,
    'Item' => [
        'Id' => [ 'N' => '104' ], // Primary Key
        'Title' => [ 'S' => 'Book 104 Title' ],
        'ISBN' => [ 'S' => '333-3333333333' ],
        'Price' => [ 'N' => '2000' ],
        'Authors' => [ 'SS' => [
                'Author1', 'Author2', 'Author3' ] 
        ]   
    ],  
    'ExpressionAttributeNames' =>  [
        '#I' => 'ISBN'] ,
            
    'ExpressionAttributeValues' =>  [
        ':val1' => ['S' => '333-3333333333']] ,
    'ConditionExpression' => '#I = :val1',
    'ReturnValues' => 'ALL_OLD' 
]);

print_r ($result);

For more information, see PutItem.

Getting an Item

The getItem function retrieves a single item. To retrieve multiple items, you can use the batchGetItem method (see Batch Get: Getting Multiple Items).

The following PHP code snippet demonstrates the preceding steps. The code gets the item that has the specified partition key.

Note

This code sample assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Creating Tables and Loading Sample Data section. Alternatively, you can load the data using the instructions in the Creating Example Tables and Uploading Data Using the AWS SDK for PHP topic.

For step-by-step instructions to run the following example, see PHP Code Samples.


$response = $dynamodb->getItem([
    'TableName' => 'ProductCatalog',
    'Key' => [
        'Id' => [ 'N' => '104' ]
    ]
]);

print_r ($response['Item']);

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters for the getItem function. For example, the following PHP code snippet uses an optional method to retrieve only a specific list of attributes, and requests a strongly consistent return value. The code specifies the following optional parameters:

  • A specific list of attribute names, including the Id and Authors.

  • A Boolean value that requests a strongly consistent read value. Read results are eventually consistent by default. You can request read results to be strongly consistent. To learn more about read consistency, see Read Consistency.


$response = $dynamodb->getItem([
    'TableName' => 'ProductCatalog',
    'Key' => [
        'Id' => ['N' => '104'],
    ],
    'ProjectionExpression' => 'Id, Authors',
    'ConsistentRead' => true
]);

For more information, see GetItem.

Batch Write: Putting and Deleting Multiple Items

The AWS SDK for PHP batchWriteItem function enables you to put or delete several items from multiple tables in a single request.

The following PHP code snippet performs the following write operations:

  • Put an item in the Forum table.

  • Put and delete an item from the Thread table.

For more information, see BatchWriteItem.

Note

This code sample assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Creating Tables and Loading Sample Data section. Alternatively, you can load the data using the instructions in the Creating Example Tables and Uploading Data Using the AWS SDK for PHP topic.

For step-by-step instructions to run the following example, see PHP Code Samples.


$tableNameOne = 'Forum';
$tableNameTwo = 'Thread';

$response = $dynamodb->batchWriteItem([
    'RequestItems' => [
        $tableNameOne => [
            [
                'PutRequest' => [
                    'Item' => [
                        'Name'   => ['S' => 'Amazon S3 Forum'],
                        'Threads' => ['N' => '0']
                    ]]
            ]
        ],
        $tableNameTwo => [
            [
                'PutRequest' => [
                    'Item' => [
                        'ForumName'   => ['S' => 'Amazon S3 Forum'],
                        'Subject' => ['S' => 'My sample question'],
                        'Message'=> ['S' => 'Message Text.'],
                        'KeywordTags'=>['SS' => ['Amazon S3', 'Bucket']]
                    ]]
            ],
            [
                'DeleteRequest' => [
                    'Key' => [
                        'ForumName' =>['S' => 'Some partition key value'],
                        'Subject' => ['S' => 'Some sort key value']
                    ]]
            ]
        ]
    ]
]);

print_r ($response['Item']);

Batch Get: Getting Multiple Items

The AWS SDK for PHP batchGetItem function enables you to retrieve multiple items from one or more tables. To retrieve a single item, you can use the getItem method.

The following PHP code snippet retrieves two items from the Forum table and three items from the Thread table.

Note

This code sample assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Creating Tables and Loading Sample Data section. Alternatively, you can load the data using the instructions in the Creating Example Tables and Uploading Data Using the AWS SDK for PHP topic.

For step-by-step instructions to run the following example, see PHP Code Samples.


date_default_timezone_set('UTC');
$sevenDaysAgo = date('Y-m-d H:i:s', strtotime('-7 days'));
$twentyOneDaysAgo = date('Y-m-d H:i:s', strtotime('-21 days'));

$response = $dynamodb->batchGetItem([
    'RequestItems' => [
        'Forum' => [
            'Keys' => [
                [
                    'Name'  => [ 'S' => 'DynamoDB' ]
                ]
            ]
        ],
        'Reply' => [
            'Keys' => [
                [ 
                    'Id'  => [ 'S' => 'DynamoDB#DynamoDB Thread 2'],
                    'ReplyDateTime' => [ 'S' => $sevenDaysAgo],
                ],
                [ 
                    'Id'  => [ 'S' => 'DynamoDB#DynamoDB Thread 2'],
                    'ReplyDateTime' => [ 'S' => $twentyOneDaysAgo],
                ],
            ]
        ]
    ]
]);

print_r($response['Responses']);

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters for the batchGetItem function. For example, you can specify a list of attributes to retrieve, as shown in the following PHP code snippet. The code retrieves two items from the Forum table and uses the ProjectionExpression parameter to retrieve the count of threads in each table:


$response = $dynamodb->batchGetItem([
    'RequestItems' => [
        'Forum' => [
            'Keys' => [
                [ 
                    'Name'  => [ 'S' => 'Amazon S3' ]
                ],
                [ 
                    'Name'  => [ 'S' => 'DynamoDB' ]
                ]
            ],
            'ProjectionExpression' => 'Threads'
        ],
    ]
]);

print_r($response);

For more information, see BatchGetItem.

Updating an Item

Use the updateItem function to update existing attribute values, add new attributes to the existing collection, or delete attributes from the existing collection.

The updateItem function uses the following guidelines:

  • If an item does not exist, the updateItem function adds a new item using the primary key that is specified in the input.

  • If an item exists, the updateItem function applies the updates as follows:

    • Replaces the existing attribute values with the values in the update.

    • If the attribute you provide in the input does not exist, it adds a new attribute to the item.

    • If you use ADD for the Action, you can add values to an existing set (string or number set), or mathematically add (use a positive number) or subtract (use a negative number) from the existing numeric attribute value.

Note

The putItem function (Putting an Item) also updates items. For example, if you use putItem to upload an item and the primary key exists, the operation replaces the entire item. If there are attributes in the existing item and those attributes are not specified in the input, the putItem operation deletes those attributes. However, updateItem only updates the specified input attributes so that any other existing attributes of that item remain unchanged.

The following PHP code snippet updates a book item in the ProductCatalog table. It adds a new author to the set of Authors and deletes the existing ISBN attribute. It also reduces the price by one.

Note

This code sample assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Creating Tables and Loading Sample Data section. Alternatively, you can load the data using the instructions in the Creating Example Tables and Uploading Data Using the AWS SDK for PHP topic.

For step-by-step instructions to run the following example, see PHP Code Samples.


$response = $dynamodb->updateItem([
    'TableName' => 'ProductCatalog',
    'Key' => [
        'Id' => [ 'N' => '201' ]
    ],
    'ExpressionAttributeValues' =>  [
        ':val1' => [
            'S' => 'Author YY',
            'S' => 'Author ZZ'],
        ':val2' => ['N' => '1'] 
    ] ,
    'UpdateExpression' => 'set Authors = :val1, Price = Price - :val2 remove ISBN'
]);

print_r($response);

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters for the updateItem function including an expected value that an attribute must have if the update is to occur. If the condition you specify is not met, then the AWS SDK for PHP throws a ConditionalCheckFailedException. For example, the following PHP code snippet conditionally updates a book item price to 25. It specifies the following optional parameters:

  • A ConditionExpression parameter that sets the condition that the price should be updated only if the existing price is 20.00.

  • A ALL_NEW value for the ReturnValues parameter that specifies the response should include all of the item's current attribute values after the update.


$response = $dynamodb->updateItem([
    'TableName' => 'ProductCatalog',
    'Key' => [
        'Id' => [
            'N' => '201'
        ]
    ],
    'ExpressionAttributeValues' =>  [
        ':val1' => ['N' => '22'], 
        ':val2' => ['N' => '20']
    ] ,
   'UpdateExpression' => 'set Price = :val1',
   'ConditionExpression' => 'Price = :val2',
   'ReturnValues' => 'ALL_NEW'
]);

print_r($response);

For more information, see UpdateItem>.

Atomic Counter

You can use updateItem to implement an atomic counter, where you increment or decrement the value of an existing attribute without interfering with other write requests. To update an atomic counter, use updateItem with an appropriate UpdateExpression.

The following code snippet demonstrates this, incrementing the Quantity attribute by one.


$response = $dynamodb->updateItem([
    'TableName' => 'ProductCatalog',
    'Key' => [
        'Id' => ['N' => '201']
    ],
    'ExpressionAttributeValues' => [
        ':val1' => ['N' => '1']
    ] ,
    'UpdateExpression' => 'set Quantity = Quantity + :val1',  
    'ReturnValues' => 'ALL_NEW'
]);

print_r($response['Attributes']);

Deleting an Item

The deleteItem function deletes an item from a table.

Note

This code sample assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Creating Tables and Loading Sample Data section. Alternatively, you can load the data using the instructions in the Creating Example Tables and Uploading Data Using the AWS SDK for PHP topic.

For step-by-step instructions to run the following example, see PHP Code Samples.


$response = $dynamodb->deleteItem([
    'TableName' => 'ProductCatalog',
    'Key' => [
        'Id' => [
            'N' => '101'
        ]
    ]
]);

print_r($response);

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters for the deleteItem function. For example, the following PHP code snippet specifies the following optional parameters:

  • An Expected parameter specifying that the Book item with Id value '103' in the ProductCatalog table be deleted only if the book is no longer in publication. Specifically, delete the book if the InPublication attribute is false.

  • A RETURN_ALL_OLD enumeration value for the ReturnValues parameter requests that the response include the item that was deleted and its attributes before the deletion.


$$tableName = 'ProductCatalog';

$response = $dynamodb->deleteItem ([
    'TableName' => $tableName,
    'Key' => [
        'Id' => [
            'N' => '103'
        ]
    ],
    'ExpressionAttributeValues' => [
        ':val1' => ['BOOL' => false]
    ],
    'ConditionExpression' => 'InPublication = :val1',
    'ReturnValues' => 'ALL_OLD'
]);

print_r($response);

For more information, see DeleteItem.