代码"/>
【已验证】微信小程序php连接SQL Server数据库代码
微信实现通过PHP连接到数据库,分为三步:首先写index.php的接口代码,然后在微信小程序的js页面上调用php接口方法连接到数据库(通过url地址的方式),最后在小程序的wxml页面将控制台的数据显示在页面上。
微信小程序连接远程数据库的代码实现需要使用后端语言(如 PHP 等)实现 Web 接口,然后在小程序端通过请求该接口获取数据。
具体实现步骤如下:
在后端服务器上搭建并配置数据库。
在后端服务器上编写 Web 接口,用于访问数据库并返回数据。
在微信小程序端使用 wx.request() 方法发送 HTTP 请求,请求后端接口并获取数据。
以下是使用 PHP 编写的示例代码:
一、实现的界面
数据库中的数据
服务端php
<?php
$serverName = "alrks,568"; //数据库服务器地址
$uid = "tt_db"; //数据库用户名
$pwd = "abab1356"; //数据库密码
$connectionInfo = array("UID"=>$uid, "PWD"=>$pwd, "Database"=>"DBAliSys");
$conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn === false )
{ echo "Could not connect.\n"; die( print_r( sqlsrv_errors(), true));
} /* Set up and execute the query. */
$tsql = " select * from tb_users where username='3'";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false)
{ echo "Error in query preparation/execution.\n"; die( print_r( sqlsrv_errors(), true));
} /* Retrieve each row as an associative array and display the results.*/
$rows = array();while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{ //echo $row['LastName'].", ".$row['FirstName']."\n"; $rows[] = $row;} // 将数组转换为JSON字符串并输出
echo json_encode($rows);/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
微信小程序端
index5.js
// pages/index/index5.js
Page({/*** 页面的初始数据*/data: {items:[]},/*** 生命周期函数--监听页面加载*/onLoad(options) {var that = this;wx.request({url: "http://127.0.0.1:8081/sql/sql311.php",success: function (rep){console.log(rep);/*将数据输出在控制台数据查看*/that.setData({items: rep.data/*将数据暂存到items数组中*/});}}) /*获取项目库的数据*/},/*** 生命周期函数--监听页面初次渲染完成*/onReady() {},/*** 生命周期函数--监听页面显示*/onShow() {},/*** 生命周期函数--监听页面隐藏*/onHide() {},/*** 生命周期函数--监听页面卸载*/onUnload() {},/*** 页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh() {},/*** 页面上拉触底事件的处理函数*/onReachBottom() {},/*** 用户点击右上角分享*/onShareAppMessage() {}
})
index5.wxml
<!--pages/index/index5.wxml-->
<view wx:for="{{items}}"><view>{{item.username}},{{item.email}},{{item.phone}}</view>
</view>
显示在小程序的页面上
更多推荐
【已验证】微信小程序php连接SQL Server数据库代码
发布评论