微信小程序是不能直接連接數(shù)據(jù)庫進(jìn)行數(shù)據(jù)操作的,這是出于安全的考慮?;旧隙际窍韧ㄟ^wx.request向服務(wù)器發(fā)起請求,再由服務(wù)端程序(如PHP)來對MySQL數(shù)據(jù)庫進(jìn)行數(shù)據(jù)操作。
微信小程序怎么連接到數(shù)據(jù)庫
1、在微信小程序的index.js文件中編寫請求數(shù)據(jù)庫的小程序代碼;文章來源:http://www.zghlxwxcb.cn/news/detail-720616.html
var app = getApp()
Page({
????onLoad: function () {
????????wx.request({
????????????url: 'http://localhost', //服務(wù)器地址
????????????data: {
????????????????name: 'bob'//請求參數(shù)
????????????},
????????????header: {
????????????????'content-type': 'application/json'
????????????},
????????????success: function (res) {
????????????????console.log(res.data)
????????????}
????????})
????}
})
2、 用PHP編寫后臺服務(wù)器響應(yīng)代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-720616.html
<?php
$name=$_GET["name"] ;//接收參數(shù)
$conn = mysqli_connect("localhost", "test","root","root");//連接MYSQL數(shù)據(jù)庫
$sql = "SELECT name,age FROM xcx WHERE name='$name'";//響應(yīng)請求
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {// 輸出小程序數(shù)組
????while($row = mysqli_fetch_assoc($result)) {
????????echo json_encode($row);//將請求結(jié)果轉(zhuǎn)換為json格式
????}
}
?>
到了這里,關(guān)于微信小程序怎么連接到數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!