微信小程式連線MySQL資料庫(讀取+寫入)demo
阿新 • • 發佈:2021-12-15
通過php檔案進行資料中轉。經試驗有效可行!!!
1、php 部分
1.1、連線資料庫
connect_error) {
echo "系統異常,連線資料庫失敗";
}
else
{
echo "連線成功";
}*/
?>
1.2、讀取php
connect_error) { die("連線失敗:".$con->connect_error); } else { $sql="SELECT * FROM `1students` WHERE `name` = '$something' ";//根據傳入的引數查詢資料庫中的資料 $res=$con->query($sql); echo $con->error; print_r($res->fetch_all (MYSQLI_BOTH)); if ($res){ $data=$res->fetch_all(PDO::FETCH_LAZY); } else{ echo '查詢出錯!'; } //fetch_all查詢所有行 echo json_encode($data);//返回二維陣列形式的值供小程式端用 } ?>
1.3、寫入php
connect_error) { die("連線失敗:".$con->connect_error); } else { $sql="INSERT INTO `1students`(`name`, `age`, `xb`) VALUES ('$something1','$something2','$something3');"; $res=$con->query($sql); if($res){ $arr['status'] = 1; $arr['info'] = 'success'; }else{ $arr['status'] = 0; $arr['info'] = 'error'; } echo json_encode($arr); die; } ?>
2、微信小程式部分
直接貼程式碼:
2.1、js部分:
onLoad: function() { var that = this; //讀取資料庫 wx.request({ url: 'http://127.0.0.1/get.php', method: 'GET', data: { something: '1' }, header: { 'content-Type': 'application/json' }, success(res) { console.log(res), that.setData({ postList: res.data, }); } }); //寫入資料庫 wx.request({ url: 'http://127.0.0.1/post.php', method: 'GET', data: { something1: '小王', something2: '16', something3: '0' }, header: { 'content-Type': 'application/x-www-form-urlencoded' }, success(res) { console.log(res.data); if (res.data.status == 0) { wx.showToast({ title: '提交失敗!!!', icon: 'loading', duration: 1500 }) } else { wx.showToast({ title: '提交成功!!!', //這裡打印出登入成功 icon: 'success', duration: 1000 }) } } }); },
2.2、wxml部分
{{postList}}
2.3、app.json檔案中新增
"pages": [
"pages/index/index",
"pages/logs/logs",
"pages/sql/sql" //對應的位置
],
https://www.it610.com/article/1282993142190063616.htm