目录

微信小程序怎么连接到数据库

目录

微信小程序怎么连接到数据库

微信小程序是不能直接连接数据库进行数据操作的,这是出于安全的考虑。基本上都是先通过wx.request向服务器发起请求,再由服务端程序(如PHP)来对MySQL数据库进行数据操作。

https://i-blog.csdnimg.cn/blog_migrate/54996db806c11a44cfcf4db1529bbff9.jpeg

微信小程序怎么连接到数据库

1、在微信小程序的index.js文件中编写请求数据库的小程序代码;

var app = getApp()

Page({

    onLoad: function () {

        wx.request({

            url: 'http://localhost', //服务器地址

            data: {

                name: 'bob'//请求参数

            },

            header: {

                'content-type': 'application/json'

            },

            success: function (res) {

                console.log(res.data)

            }

        })

    }

})

2、 用PHP编写后台服务器响应代码

<?php

$name=$_GET["name"] ;//接收参数

$conn = mysqli_connect("localhost", "test","root","root");//连接MYSQL数据库

$sql = "SELECT name,age FROM xcx WHERE name='$name'";//响应请求

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {// 输出小程序数组

    while($row = mysqli_fetch_assoc($result)) {

        echo json_encode($row);//将请求结果转换为json格式

    }

}

?>