当前位置:   article > 正文

微信小程序取本地数据库数据(实测有图)_微信小程序怎么读取数据库里的图片csdn

微信小程序怎么读取数据库里的图片csdn

测试效果如下:
在这里插入图片描述

本实验主要分为如下几个步骤:
一、安装数据库
二、安装PHP+Apache
三、编辑微信小程序代码
前两项的简单介绍在如下连接:
PHP+Apache
四、本文主要介绍第三项的内容
需要用到的文件如下:
1、新建微信小程序工程
2、在index/index.js中操作如下:

Page({
 data:{
    data:[]  //添加变量,用于前端页面显示
  }
})

onLoad() {
    let that = this;
	wx.request({
      url: 'http://localhost/api.php',
      data:{},
      method:'GET',
      header:{
        'content-Type':'application/json'
      },
      success:function(res){
        that.setData({
          data:res.data,
        });
      }
    })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

3、在index.wxml中添加如下内容

<!--index.wxml-->
<view class="container">
  <view wx:for="{{data}}">
  {{item}}
</view>
</view>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4、在Apache软件的路径下的C:\Apache24\htdocsphp放置如下php文件
selectData.php

<?php
$sername = "localhost";//服务名称
$uname = "root";//数据库访问用户名
$pwd = "mima";//数据库密码
$dbname = "db2";//建立的数据库

//创建连接
$conn = new mysqli($sername,$uname,$pwd,$dbname);
$conn->set_charset("utf8");
if($conn->connect_error)
{
	die("连接失败:".$conn->connect_error);
}
$sql = "SELECT id, type FROM tab1";//数据查询指令
$result = $conn->query($sql);
$data = $result->fetch_all();
echo json_encode($data);//json格式输出
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

在Apache24目录C:\Apache24\htdocs下放置如下php文件
connSql.php

<?php
    
    $mysql =new mysqli("localhost","root","mima","db2");
    if ( !$mysql){
        die('数据库链接失败!'.$mysql->connection_error);
    }
    echo '<h1 style="color:red">数据库链接成功!</h1>';
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

5、启动Mysql、apache
管理员打开cmd
在这里插入图片描述
net start mysql 指令启动mysql
在这里插入图片描述
主要用到的数据库指令如下:

create database 数据库名
drop database 数据库名  (空数据库)
创建表:create table tab1(id int auto_increment not null primary key, type varchar(40) not null);
insert into tab1 values(序号,类型);
select *from tab1;
net start apache指令启动apache
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

建立如下图数据库
在这里插入图片描述

在这里插入图片描述
测试apache启动成功与否,成功如下所示:
在这里插入图片描述

浏览器测试连接数据库,在浏览器输入
在这里插入图片描述
浏览器查看数据库内容如下:
在这里插入图片描述
微信小程序查看数据库内容下:
在这里插入图片描述
四、插入数据到本地数据库,模拟云端数据库

<?php
$sername = "127.0.0.1:3306";
$uname = "root";
$pwd = "mima";
$dbname = "db2";

//创建连接
$conn = new mysqli($sername,$uname,$pwd,$dbname);
$conn->set_charset("utf8");
if($conn->connect_error)
{
	die("连接失败:".$conn->connect_error);
}
$sql = "insert into tab2 (telphone,pwd)values(17700006613,1213)";//插入数据到本地电脑数据库
$result = $conn->query($sql);
$data = $result->fetch_all();
echo json_encode($data);
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/464825
推荐阅读
相关标签
  

闽ICP备14008679号