Home  >  Article  >  WeChat Applet  >  How to connect WeChat applet to database

How to connect WeChat applet to database

angryTom
angryTomOriginal
2020-03-24 10:06:2929564browse

WeChat applet cannot directly connect to the database for data operations. This is for security reasons. Basically, a request is made to the server through wx.request, and then the server program (such as PHP) performs data operations on the MySQL database.

How to connect WeChat applet to database

How to connect the WeChat applet to the database

1. Write the request database in the index.js file of the WeChat applet Mini program code;

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. Use PHP to write background server response code

<?php
$name=$_GET["name"] ;//接收参数
$conn = mysqli_connect("localhost", "test","root","root");//连接MYSQL数据库
$sql = "SELECT name,age FROM xcx WHERE name=&#39;$name&#39;";//响应请求
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {// 输出小程序数组
    while($row = mysqli_fetch_assoc($result)) {
        echo json_encode($row);//将请求结果转换为json格式
    }
}
?>

Recommended learning:Mini program development

The above is the detailed content of How to connect WeChat applet to database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn