t182.php

模拟接口的代码

<?php

error_reporting(0);
/**
 *
 *
 */
//显示
function show($id=0)
{
    //实例化pdo
    $pdo = new PDO('mysql:dbname=test;host=localhost','root','mysql123');
    //查询语句,:id表示绑定
    $sql = "select * from user where user_id=:id";
    //设置字符集
    $pdo->query("set names utf8");
    //准备
    $result = $pdo->prepare($sql);
    //绑定变量,执行
    $result->execute(array('id'=>$id));
    //取数据
    $user = $result->fetch(PDO::FETCH_ASSOC);
    //空值,返回错误提示
    if(empty($user))
    {
        $user = array("errorno"=>"SN001","errormsg"=>"没有找到数据!");
    }
    return $user;
}

//存储方法
function store($user)
{

    $pdo = new PDO('mysql:dbname=test;host=localhost','root','mysql123');
    //插入语句,?为占位符
    $sql = "insert into user(user_name,sex,age,description) values (?,?,?,?)";
    $pdo->query("set names utf8");
    //准备
    $result = $pdo->prepare($sql);
    //绑定,数组方式的变量
    $result->execute([$user['user_name'],$user['sex'],$user['age'],$user['description']]);

    //返回值大于1,表示保存成功
    if($result->rowCount() > 0)
    {
        return array("success"=>"添加成功");
    }
    //保存失败
    else
    {
        return array("errorno"=>"SN003","errormsg"=>"数据添加失败!");
    }

}

//判断是GET方式
if('GET' == $_SERVER['REQUEST_METHOD'])
{
    //用户id
    $id = $_GET['id']?? 0;
    //有值,显示
    if($id)
    {
        $user = show($id);
    }
    //无值,返回错误提示
    else
    {
        $user = array("errorno"=>"SN002","errormsg"=>"参数ID错误!");
    }
    //返回json格式的数据
    echo json_encode($user);
}
//判断是POST方式
elseif('POST' == $_SERVER['REQUEST_METHOD'])
{
    //POST数组不为空
    if(!empty($_POST))
    {
        //保存数据,返回值解码json格式
        echo json_encode(store($_POST));
    }
    //POST数组为空
    else
    {
        echo json_encode(array("errorno"=>"SN004","errormsg"=>"数据提交失败!"));
    }
}

t183.php

调用接口

<?php
//GET方式
function get($url)
{
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_TIMEOUT,10);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res,true);
}
//POST方式
function post($url,array $data)
{
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    curl_setopt($ch,CURLOPT_TIMEOUT,10);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res,true);
}
//没有id值,
print_r(get('http://localhost:8081/t182.php'));
echo "<br>";
//id=1时
print_r(get('http://localhost:8081/t182.php?id=1'));
echo "<br>";
//保存,数组为空时
print_r(post('http://localhost:8081/t182.php',array()));
echo "<br>";
//数组有值
$user = ["user_name"=>"uu",'sex'=>'女','age'=>'19','description'=>"ok"];
//print_r($user);
print_r(post('http://localhost:8081/t182.php',$user));
echo "<br>";