一、实验目的
- 掌握 phpStudy 集成环境的搭建与 Apache、MySQL 服务的启动;
- 掌握 Navicat 连接 MySQL、建库建表、查看数据;
- 掌握 ThinkPHP8 的安装、数据库配置与控制器接口开发;
- 掌握微信小程序页面开发与
wx.request网络请求,实现前后端数据交互。
整体结构:
微信小程序(登录页 / 成绩页)
↓ wx.request(HTTP GET/POST)
ThinkPHP8 接口(readLogin / readScore)
↓ PDO
MySQL 数据库 test(login 表 / score 表)
二、环境搭建
2.1 启动 phpStudy
打开 phpStudy,在首页分别启动 Apache2.4.39 和 MySQL5.7.26,两者状态变为"已启动"。
【截图1:phpStudy 首页,Apache 和 MySQL 均为已启动状态】
Apache 的网站根目录为 D:\phpstudy_pro\WWW,访问 http://localhost 即可打开该目录。
2.2 准备 PHP 与扩展
ThinkPHP8 要求 PHP ≥ 8.1,且必须开启 PDO 的 MySQL 驱动。在 phpStudy 的 PHP 目录中找到 php.ini,确认以下扩展已启用:
ini
extension=pdo_mysql
extension=mysqli
extension=curl
extension=mbstring
extension=openssl
extension=zip
extension=fileinfo
可以用命令验证:
bat
php -m | findstr pdo_mysql
2.3 安装 ThinkPHP8
在 WWW 目录下打开命令行,使用 Composer 创建项目:
bat
cd /d D:\phpstudy_pro\WWW
composer create-project topthink/think thinkphp
安装完成后,目录结构如下(只列关键部分):
thinkphp\
app\controller\Index.php
config\database.php
public\index.php
.env
浏览器访问 http://localhost/thinkphp/public/index.php 出现 ThinkPHP 欢迎页即安装成功。
三、数据库设计
3.1 创建数据库与数据表
在 Navicat 中连接本机 MySQL(localhost:3306),新建数据库 test,字符集 utf8mb4。
登录表 login:
sql
CREATE TABLE `login` (
`username` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `login` VALUES ('yaoxinchun', '123456');
成绩表 score:
sql
CREATE TABLE `score` (
`stuID` varchar(20) NOT NULL,
`name` varchar(20) NOT NULL,
`age` int(11) DEFAULT NULL,
`score` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `score` VALUES
('24103073', '姚鑫淳', 20, 100),
('24103025', '李时仪', 20, 100),
('24105021', '迟彤', 20, 100),
('24105068', '吕冰冰', 20, 100);
【截图2:Navicat 中 test 库下的 login 表数据】
【截图3:Navicat 中 test 库下的 score 表数据】
3.2 创建数据库账号
为了方便项目连接,单独创建一个只拥有 test 库权限的账号:
sql
CREATE USER 'mytest'@'localhost' IDENTIFIED BY 'mytest';
GRANT ALL PRIVILEGES ON test.* TO 'mytest'@'localhost';
FLUSH PRIVILEGES;
四、服务端接口开发
4.1 配置数据库连接
修改项目根目录的 .env 文件:
ini
APP_DEBUG = true
DB_TYPE = mysql
DB_HOST = 127.0.0.1
DB_NAME = test
DB_USER = mytest
DB_PASS = mytest
DB_PORT = 3306
DB_CHARSET = utf8mb4
ThinkPHP8 的 config/database.php 默认通过 env() 读取上述配置,因此只需要改 .env 即可。
4.2 编写查询接口
编辑 app\controller\Index.php,在原有类中新增两个方法:
php
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Db;
use think\response\Json;
class Index extends BaseController
{
public function index()
{
return 'ThinkPHP8 案例5.13';
}
// 查询登录表
public function readLogin(): Json
{
$rs = Db::table('login')->select();
return json($rs);
}
// 查询成绩表
public function readScore(): Json
{
$rs = Db::table('score')->select();
return json($rs);
}
}
说明:
Db::table('login')查询test库中的login表;json($rs)把查询结果直接输出为 JSON,供小程序解析;- 返回值类型声明为
think\response\Json,避免与其他响应类型冲突。
4.3 测试接口
浏览器访问以下地址(ThinkPHP 默认的兼容模式路由):
http://localhost/thinkphp/public/index.php/index/readLogin
http://localhost/thinkphp/public/index.php/index/readScore
返回结果:
json
[{"username":"yaoxinchun","password":"123456"}]
json
[
{"stuID":"24103073","name":"姚鑫淳","age":20,"score":100},
{"stuID":"24103025","name":"李时仪","age":20,"score":100},
{"stuID":"24105021","name":"迟彤","age":20,"score":100},
{"stuID":"24105068","name":"吕冰冰","age":20,"score":100}
]
【截图4:浏览器访问 readLogin 返回 JSON】
【截图5:浏览器访问 readScore 返回 JSON】
五、微信小程序端开发
5.1 项目结构与页面注册
新建小程序项目,app.json 注册两个页面,并把首页设为登录页:
json
{
"pages": [
"pages/index/index",
"pages/score/score"
],
"window": {
"navigationBarTitleText": "案例5.13",
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black"
},
"sitemapLocation": "sitemap.json"
}
由于接口地址是本机 http://localhost,属于非备案域名,需要在开发者工具中关闭域名校验:
详情 → 本地设置 → 勾选「不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书」。
【截图6:开发者工具中勾选不校验合法域名】
5.2 登录页
登录页用 form 收集用户名密码,提交时调用 readLogin 接口,把输入值与接口返回的数组逐条比对,匹配成功则跳转成绩页。
pages/index/index.js:
javascript
const baseURL = 'http://localhost/thinkphp/public/index.php/index/readLogin'
Page({
data: {
username: '',
password: ''
},
showModal(content) {
wx.showModal({
title: '提示',
content: content
})
},
onSubmit(e) {
const info = e.detail.value
const username = info.username
const password = info.password
if (username === '' || password === '') {
this.showModal('用户名和密码不能为空!')
return
}
wx.request({
url: baseURL,
success: res => {
for (let i = 0; i < res.data.length; i++) {
if (res.data[i].username === username && res.data[i].password === password) {
wx.showModal({
title: '登录成功',
content: '用户名和密码正确',
complete: (r) => {
if (r.cancel) return
if (r.confirm) {
wx.redirectTo({ url: '../score/score' })
}
}
})
return
}
}
this.showModal('用户名或密码错误,请重新输入!')
this.setData({ username: '', password: '' })
},
fail: err => {
console.log('请求readLogin失败:', err)
}
})
}
})
pages/index/index.wxml:
xml
<view class="container">
<view class="title">案例5.13 网络和数据库</view>
<form bindsubmit="onSubmit">
<view class="row">
<text>用户名:</text>
<input name="username" placeholder="请输入用户名" />
</view>
<view class="row">
<text>密码:</text>
<input name="password" password placeholder="请输入密码" />
</view>
<button type="primary" form-type="submit">登录</button>
</form>
</view>
【截图7:小程序登录页】
5.3 成绩页
成绩页在 onLoad 中请求 readScore 接口,把返回数组绑定到 list,用 wx:for 渲染表格。
pages/score/score.js:
javascript
Page({
data: {
fields: ['学号', '姓名', '年龄', '成绩'],
list: []
},
onLoad() {
wx.request({
url: 'http://localhost/thinkphp/public/index.php/index/readScore',
method: 'POST',
success: res => {
this.setData({ list: res.data })
},
fail: e => {
console.log('调用readScore接口失败:', e)
}
})
}
})
pages/score/score.wxml:
xml
<view class="table">
<view class="tr th">
<view class="td" wx:for="{{fields}}" wx:key="*this">{{item}}</view>
</view>
<view class="tr" wx:for="{{list}}" wx:key="stuID">
<view class="td">{{item.stuID}}</view>
<view class="td">{{item.name}}</view>
<view class="td">{{item.age}}</view>
<view class="td">{{item.score}}</view>
</view>
</view>
【截图8:登录后跳转的成绩页】
5.4 运行效果
输入 yaoxinchun / 123456 登录,弹出"登录成功"后跳转成绩页,页面展示 4 条成绩,第一条为本人学号与姓名。整个链路的顺序是:
小程序 → wx.request → ThinkPHP 接口 → MySQL → JSON → 小程序渲染
六、遇到的问题与解决
1. 接口返回 500:could not find driver
原因:PHP 没有加载 pdo_mysql 扩展。
解决:在 php.ini 中开启 extension=pdo_mysql,重启 Apache 后恢复。
2. 接口返回 500:SQLSTATE[HY000] [2002] 连接被拒绝
原因:MySQL 服务没有启动,或 3306 端口被其他 MySQL 占用。
解决:在 phpStudy 中启动 MySQL;若端口被占用,先停止其他 MySQL 服务再启动。
3. Navicat 连接报 1045 - Access denied for user 'root'@'localhost'
原因:密码与数据库中实际密码不一致。
解决:使用正确密码重新输入;也可以在 Navicat 中改用项目账号 mytest / mytest。
4. 小程序请求失败 / 无数据
原因:未勾选「不校验合法域名」,或 Apache 未启动。
解决:勾选该选项;确认浏览器能正常访问接口后再运行小程序。
5. 页面空白、编译报错
原因:PHP 版本过低(ThinkPHP8 需要 ≥ 8.1)。
解决:在 phpStudy 的「网站」设置中把 PHP 版本切换为 8.2,并在 php.ini 中开启所需扩展。
七、总结
本次实验完成了从环境搭建、数据库设计、服务端接口开发到小程序端调用的完整流程,主要收获:
- 熟悉了 phpStudy 管理 Apache/MySQL 以及 PHP 扩展的配置方式;
- 掌握了 ThinkPHP8 通过
.env配置数据库、用Db门面快速查询并返回 JSON 的方法; - 掌握了小程序
wx.request发起请求、setData更新视图、页面间redirectTo跳转; - 理解了前后端分离的基本数据流:界面 → 接口 → 数据库 → JSON → 界面。
后续可以继续完善的方向:登录接口改为 POST 并在服务端校验、密码加密存储、成绩分页查询、增加 token 鉴权等。