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

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

$
0
0
PHPでApache CouchDBにアクセスして、ドキュメントデータを作成です。今回は、cUrlからPOSTでアクセス。アクセスURLの末尾にデータベース名とユニークなIDを指定すれば良いらしい。IDにはUUIDを利用することが推奨されているが、今回の例のように、重複しなければ、ユーザーIDなどでも構わない。


<?php
$ch = curl_init();

$customer = array(
'firstname' =>'太郎',
'lastname' =>'佐藤',
'username' =>'satotaro',
'email' =>'satotaro@example.com',
'pass' => md5('password')
);

$data = json_encode($customer);

curl_setopt($ch, CURLOPT_URL, 'http://admin:password@127.0.0.1:5984/customers/'.$customer['username']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
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": "satotaro",
"rev": "1-1a3df21386acf40bf4364936146ab062"
}
「id」が重複して失敗の場合

{
"error": "conflict",
"reason": "Document update conflict."
}

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

Viewing all articles
Browse latest Browse all 846

Trending Articles