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 @   兔咂  阅读(373)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示