查看: 685|回复: 0

客户端调用api接口以及php接口创建实例

[复制链接]

748

主题

39

回帖

3907

积分

管理员

总舵主

积分
3907
QQ
发表于 2024-5-25 20:04:36 | 显示全部楼层 |阅读模式
php开发接口实例代码:
  1. /*这是PHP创建的一个小接口*/

  2. <?php
  3. $mysqli = new mysqli('localhost', 'root', '123456','interfacetest');
  4. mysqli_query($mysqli,"set names utf8");
  5. if ($mysqli->connect_error) {
  6.     die('Connect Error (' . $mysqli->connect_errno . ') '
  7.             . $mysqli->connect_error);
  8. }
  9. $output = array();
  10. $user_by= $_POST['user_by'];

  11. $uid = $_POST["uid"];
  12. if (empty($user_by)) {
  13.     $output = array('data'=>NULL, 'info'=>'this is null!', 'stats'=>1);
  14.     exit(json_encode($output));
  15. }
  16. if ($user_by == 'get_userinfo') {//调用获取用户信息的接口
  17.     //查询数据库
  18.     $sql="select * from user WHERE user_id=$uid";
  19.     $result =$mysqli->query($sql);
  20.     $userInfo = $result -> fetch_row();
  21.     if($userInfo){//如果数据存在输出数据
  22.         $output = array(
  23.             'data' => array(
  24.                 'userInfo' => $userInfo,
  25.             ),
  26.             'stats'=>0
  27.         );
  28.     }else{
  29.         $output = array(
  30.             'data' => array(
  31.                 'userInfo' => $userInfo,
  32.             ),
  33.             'stats'=>1
  34.         );
  35.     }
  36.     exit(json_encode($output));//把结果反馈给客户端
  37. }
  38. $mysqli->close();
  39. ?>
复制代码
客户端调用接口实例代码:
  1. /*这是一个接口调用的方法(post)*/
  2. $url = 'http://localhost/testmysql.php';
  3. $sl_data=array(
  4.     'uid'=>1,
  5.     'user_by'=>'get_userinfo'
  6. );
  7. $ch = curl_init();
  8. curl_setopt($ch, CURLOPT_URL, $url);//要访问的地址
  9. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);//执行结果是否被返回,0是返回,1是不返回
  10. curl_setopt($ch, CURLOPT_POST, 1);// 发送一个常规的POST请求
  11. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($sl_data));
  12. $output = curl_exec($ch);//执行并获取数据
  13. echo $output;
  14. curl_close($ch);
复制代码
这就是简单的接口创建与调用。
道不同,不相为谋!理想要有,万一实现了呢?
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注公众号

相关侵权、举报、投诉及建议等,请发 E-mail:2513533699@qq.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.|鲁ICP备19000917号|鲁公网安备37078302000320号

在本版发帖
关注公众号
QQ客服返回顶部