微信小程序实现获取用户信息并存入数据库操作示例
本文实例讲述了微信小程序实现获取用户信息并存入数据库操作。分享给大家供大家参考,具体如下:
微信小程序获取用户信息简单,但是在存入自己服务器数据库的过程中研究了一天多的时间,并且网上搜索不到该资源,故发出来供大家参考。
index.js
Page({ data: { nickName: "微信账号登录", avatarUrl:"./user-unlogin.png", }, onLoad: function () { var that = this; var nickName = that.data.nickName ; var avatarUrl = that.data.avatarUrl; var db="no"; wx.getUserInfo({ success: function (res) { that.data.nickName = res.userInfo.nickName, that.data.avatarUrl = res.userInfo.avatarUrl, that.setData({ nickName: that.data.nickName, avatarUrl: that.data.avatarUrl, }), that.setData({ db:"ok"// 设置变量db,只有成功获取用户信息后才写入数据库 }) if(db = "ok") { var name, url; wx.request({ url: 'https://.../getuserinfo.php',//写自己的服务器 header: { "Content-Type": "application/x-www-form-urlencoded" }, method: "POST", data: { name: res.userInfo.nickName, url: res.userInfo.avatarUrl, }, success: function () { console.log("success") }, fail: function () { console.log("fail") } }) } }, fail: function (res) { that.data.nickName = "未授权无法获取用户信息", that.setData({ nickName: that.data.nickName }) } }) }, onShow: function () { } })
getuserinfo.php
<?php $name = $_POST['name']; $url = $_POST['url']; $servername = "localhost"; $username = "root"; $password = "";//服务器中连接数据库的密码 $dbname = "mydb";//使用的数据库名 // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("connect server fail: " . $conn->connect_error); } $sql = "INSERT INTO userinfo VALUES ('$name', '$url')"; if ($conn->query($sql) === TRUE) { echo "insert success"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
测试通过,在服务器中查询有用户信息
希望本文所述对大家微信小程序开发有所帮助。
相关推荐
kgshuo 2020-09-25
Tomato 2020-09-10
taiyangyu 2020-09-10
CodeAndroid 2020-09-10
small 2020-07-29
sucheng 2020-07-26
zuoliangzhu 2020-07-20
CodeAndroid 2020-07-14
xiaoxubbs 2020-07-04
sucheng 2020-06-25
kgshuo 2020-06-14
意外金喜 2020-06-14
zuoliangzhu 2020-06-14
tianping 2020-06-14
hgzhang 2020-06-14
killgod 2020-06-14
戴翔的技术 2020-06-14
郴州小程序 2020-06-13