我在Yii中有一个RESTFul API,它具有以下功能,只需将请求中的值插入数据库。
//This is the RESFT API
public function actionUserlogin(){
$requestType = Yii::app()->request->getRequestType();
if($requestType !== 'POST'){
throw new Exception('Acces this service with POST!');
return;
}
$post = Yii::app()->request->getPost('post_data');
$command = Yii::app()->db->createCommand('INSERT INTO user (first, last)
VALUES (:first, :last)');
$command->bindParam(':first', $post['first']);
$command->bindParam(':last', $post['last']);
echo json_encode($command->execute());
}
API的网址为http://example.com/api/display 如您所见,API接受两个参数,第一个和最后一个参数。下面是我在不同PHP程序中实现的请求的代码。所以请求和API不在同一个程序中。
//This is the REST API request located in a different PHP program.
if (! isset ( $_POST ['send'] )) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="email">Enter User Email <br />
<input type="text" name="password">Password <br />
<input type="submit" name="send" value="Select"> <br />
</form>
$service_url = 'http://example.com/api/display';
$curl = curl_init ( $service_url );
$post_data = array (
'first' => $_POST ['first'],
'last' => $_POST ['last']
);
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $curl, CURLOPT_POST, true );
curl_setopt ( $curl, CURLOPT_POSTFIELDS, $post_data );
$curl_response = curl_exec ( $curl );
if ($curl_response === false) {
$info = curl_getinfo ( $curl );
curl_close ( $curl );
die ( 'error occured during curl exec. Additioanl info: ' . var_export ( $info
) );
}
curl_close ( $curl );
$decoded = json_decode ( $curl_response );
if (isset ( $decoded->response->status ) && $decoded->response->status == 'ERROR') {
die ( 'error occured: ' . $decoded->response->errormessage );
}
echo 'response ok!';
var_export ( $decoded->response );
出于某种原因,似乎API无法从请求中获取参数“First and last”。请求不传递在表单中输入的这些参数,因此无法在数据库中插入数据。
任何想法或解决方案都将受到高度赞赏。