Quantcast
Channel: 一言多いプログラマーの独り言
Viewing all articles
Browse latest Browse all 846

PHPでApache CouchDBにアクセスして、ドキュメントデータを更新

$
0
0
PHPでApache CouchDBにアクセスして、ドキュメントデータを更新です。 アクセスURLの末尾に、データベース名とドキュメントIDを指定し、「'_rev'」データを用意する必要があります。更に、PUTでアクセスするのがミソのようです。


<?php
$id = '5945d346-f70e-46bb-886f-2dc88465dfe5';

$customer = array(
'firstname' =>'二郎',
'lastname' =>'佐藤',
'username' =>'satojiro',
'email' =>'satojiro@example.com',
'pass' => md5('password')
);
$customer['_rev'] = '2-12860c046ac06d030644c4ecd8f53a10';
$data = json_encode($customer);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://admin:password@127.0.0.1:5984/customers/'.$id);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Accept: */*'
));
$response = curl_exec($ch);
curl_close($ch);

header('content-type: application/json; charset=utf-8');
echo $response ;
?>
成功の場合

{
"ok": true,
"id": "5945d346-f70e-46bb-886f-2dc88465dfe5",
"rev": "3-876acc4794d3dd97c54d400ede5ce1aa"
}
_rev が正しくない場合

{
"error": "conflict",
"reason": "Document update conflict."
}
POSTでアクセスした場合

{
"error": "bad_request",
"reason": "Referer header required."
}

参考サイト
CouchDB for PHP developers - CRUD(Inchooさん)

Viewing all articles
Browse latest Browse all 846

Latest Images

Trending Articles