Micro-channel connected to a database applet

1, login applet background -> Development -> Development Settings -> domain name server settings ( the protocol must be https or wss, https protocols need to turn on SSL certificate ), as shown:

Here Insert Picture Description
If debug locally, can be set as follows:

Here Insert Picture Description
2, .wxml file:

<view wx:for="{{info}}" wx:key="key">
	<text>{{item.id}} {{item.nicheng}} {{item.content}} {{item.time}}</text>
</view>

3, .js file Page in:

/**
* 页面的初始数据
*/
data: {
	info: []						//将info的数据传到前台wxml页面中
},

/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
	var that = this
	wx.request({
		url: 'http://localhost:88/chat/test.php',		//此处不能用https
		data: {},
		header: {
			'content-type': 'application/json'
		},
		success: function(res) {
			console.log(res.data)
			that.setData({
				info: res.data		//设置数据,将表中查询出来的信息传给info
			})
		},
		fail: function(err) {
			console.log(err)
		}
	})
},

4, background php page:

<?php		
// 设置数据库IP,账号,密码
$conn = mysql_connect("127.0.0.1", "username", "password")or die("Mysql Connect Error");
// 数据库库名
mysql_select_db("chat");
// 设置编码,否则可能会出错
mysql_query("SET NAMES UTF8");
// 设置时区,避免出错
ini_set("date.timezone", "PRC");
$sql = "select * from chat order by id asc";
$result = mysql_query($sql, $conn);
if (mysql_num_rows($result) > 0) {// 输出小程序数组
	$data = array();
	while($row = mysql_fetch_array($result)){
		//键值对必须用""包裹,不能用'',否则会报错
        $zifu = '{"id":"'.$row['id'].'","nicheng":"'.$row['nicheng'].'","content":"'.$row['content'].'","time":"'.date("Y-m-d H:i:s", $row['time']).'"}';
        //将json格式的字符串解码成对象,加true参数时解码成数组
        $data[] = json_decode($zifu);
	}
	//将请求结果转换为json格式,微信只能对json格式的数据进行操作
	echo json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);	
}
mysql_close($conn);
?>

The results are as follows:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qq_38882327/article/details/91377526