php获取数据库数据,并以对象形式返回

1.连接到数据库

<?php
    $servername = "";#服务器地址
    $username = "";#数据库用户名
    $password = "";#数据库密码
    $dbname = "";#数据库名

    $conn = new mysqli($servername,$username,$password,$dbname);
    if(conn->connect_error){
        die("连接失败:".$conn->connect_error);
    }
?>

2.参数接收

小程序发送请求:
wx.request({
    url:"https://www.abc.com/first.php",
    method:"GET",
    data:{
        userId:1,
        userName:aa,
    },
    success:function(result){
        console.log(result.data); #在控制台输出
    }
})
php接收参数:
$userId = $_GET['userId'];
$userName = $_GET['userName'];  

3.sql语句执行

$sql = "select userId,userName from users where userId = 1";
$result = $conn->query($sql);

$sql = "select userId,userName from users where userId = '{$userId}'"; #把获取来的参数放在sql中
$result = $conn->query($sql);

4.获取结果

$json = "";
$data = array();
class User{
    public $userId;
    public $userName;
    public $time;
}
if($result){
    while($row = $result->fetch_assoc()){
        $user = new User();
        $user->userId = $row["userId"];
        $user->userName = $row["userName"];
        $user->time = date('Y-m-d H:i',$row["time"]);#时间戳转换
        $data[]=$user;#把user变为数组(??不确定是不是数组)
    }
    $json = json_encode($data);#进行json编码
    echo $json;
}else{
    echo "0结果"
}

前端收到的数据:

  {data:[{userId:1,userName:'aaa'}]}

 

 

ps:

改了服务器地址之后要到购买域名的网站更改域名解析

如果宝塔数据库打不开,记得查看是否放行了888端口

posted @ 2020-07-15 17:16  兔咂  阅读(339)  评论(0编辑  收藏  举报