这是一个简单的接口书写
****************************************************************************
<?php
$mysqli = new mysqli('localhost', 'root', '123456','interfacetest');
mysqli_query($mysqli,"set names utf8");
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$output = array(); $a = $_POST['user_name'];
$uid = $_POST["uid"];
if (empty($a)) {
$output = array('data'=>NULL, 'info'=>'this is null!', 'code'=>-201); exit(json_encode($output));
}
if ($a == 'get_users') {//调用获取用户信息的接口 //查询数据库
$sql="select * from user WHERE user_id=$uid";
$result =$mysqli->query($sql);
$userInfo = $result -> fetch_row();
if($userInfo){//如果数据存在输出数据
$output = array(
'data' => array(
'userInfo' => $userInfo,
),
'stats'=>0
);
}else{
$output = array(
'data' => array(
'userInfo' => $userInfo,
),
'stats'=>1
);
}
exit(json_encode($output));//把结果反馈给客户端
} elseif ($a == 'get_games_result') { //...
die('您正在调 get_games_result 接口!');
} elseif ($a == 'upload_avatars') { //....
die('您正在调 upload_avatars 接口!');
}
$mysqli->close();
?>
*****************************************************************************
这是一个接口调用(post)
*****************************************************************************
<?php
$url = 'http://localhost/testmysql.php';
$sl_data=array(
'uid'=>1,
'user_name'=>'get_users'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//执行结果是否被返回,0是返回,1是不返回
curl_setopt($ch, CURLOPT_POST, 1);// 发送一个常规的POST请求
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($sl_data));
$output = curl_exec($ch);//执行并获取数据
echo $output;
curl_close($ch);