欢迎您的光临,本博所发布之文章皆为作者亲测通过,如有错误,欢迎通过各种方式指正。

文摘  微信小程序form表单提交到MYSQL实例(PHP)

小程序应用 网络 1976 0评论

小程序相对于之前的WEB+PHP建站来说,个人理解为只是将web放到了微信端,用小程序固定的格式前前端进行布局、事件触发和数据的输送和读取,服务器端可以用任何后端语言写,但是所有的数据都要以JSON的形式返回给小程序。


下面举例将个人信息提交表单到数据库实例


先来看看目录结构图

111.png

· js文件是逻辑控制,主要是它发送请求和接收数据,

· json 用于此页面局部 配置并且覆盖全局app.json配置,

· wxss用于页面的样式设置,

· wxml就是页面,相当于html


样式和json文件暂时不管了,回顾一下form表单的提交


wxml文件代码

<form bindsubmit="formSubmit" bindreset="formReset">
<view class="section">
  <view class="section__title">姓名</view>
  <input name="xingming" placeholder="请输入姓名" />
</view>
  <view class="section section_gap">
  <view class="section__title">性别</view>
  <radio-group name="xingbie">
  <label><radio value="男"/>男</label>
  <label><radio value="女"/>女</label>
  </radio-group>
  </view>
  <view class="section section_gap">
  <view class="section__title">爱好</view>
  <checkbox-group name="aihao">
  <label><checkbox value="旅游"/>旅游</label>
  <label><checkbox value="看书"/>看书</label>
  <label><checkbox value="电动"/>电动</label>
  <label><checkbox value="篮球"/>篮球</label>
  </checkbox-group>
  </view>
  <view class="btn-area">
  <button formType="submit">提交</button>
  <button formType="reset">重置</button>
  </view>
</form>


其中几个关键点需要理解:

A.Form表单,需要绑定一个submit事件,在小程序中,属性为bindsubmit,

bindsubmit=”formSubmit”这里的属性值formSubmit,命名可以为符合规范的任意值,相当于以前html中的  onsubmit=”formSubmit()”,是一个函数名,当提交的时候触发formSubmit这个函数事件,这个函数写在js中。

B.其他的属性和之前的HTML差不多,注意的是,表单一定要有name=“value”,后端处理和以前一样,比如name=”username” PHP可以用 $_POST[‘username']来接收。

C.由于小程序没有input submit这个按钮,所以在每个form表单中都要有一个提交按钮,

<button formType="submit">提交</button>,这个按钮就是用来开启提交事件的。


index.js代码:

//index.js
//获取应用实例
const app = getApp()
Page({
data: {
},
formSubmit: function (e) {    
//console.log(e.detail.value);
if (e.detail.value.xingming.length == 0 || e.detail.value.xingming.length >= 8) {
wx.showToast({
title: '姓名不能为空或过长!',
icon: 'loading',
duration: 1500
})
setTimeout(function () {
wx.hideToast()
}, 2000)
} else if (e.detail.value.xingbie.length == 0) {
wx.showToast({
title: '性别不能为空!',
icon: 'loading',
duration: 1500
})
setTimeout(function () {
wx.hideToast()
}, 2000)
} else if (e.detail.value.aihao.length == 0) {
wx.showToast({
title: '爱好不能为空!',
icon: 'loading',
duration: 1500
})
setTimeout(function () {
wx.hideToast()
}, 2000)
} else {
wx.request({
url: 'https://www.xxxxx.com/wx/form.php',
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST",
data: { xingming: e.detail.value.xingming, xingbie: e.detail.value.xingbie, aihao: e.detail.value.aihao },
success: function (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
})
}
}
})
}
},
})


需要注意的是

Page()这个方法是必须有的,里面放置js对象,用于页面加载的时候,呈现效果

data: {} 数据对象,设置页面中的数据,前端可以通过读取这个对象里面的数据来显示出来。

formSubmit: function 小程序中方法都是 方法名:function(),其中function可以传入一个参数,作为触发当前时间

的对象下面是函数的执行,由于验证太多,我只拿一部分出来理解。

if (e.detail.value.xingming.length == 0 || e.detail.value.xingming.length >= 8) {
wx.showToast({
title: '姓名不能为空或过长!',
icon: 'loading',
duration: 1500
})
setTimeout(function () {
wx.hideToast()
}, 2000)
}

这里的e,就是当前触发事件的对象,类似于html onclick=“foo(this)”this对象,小程序封装了许多内置的调用方法,

e.detail.value.xingming就是当前对象name=”xingming”的对象的值, e.detail.value.xingming.length就是这

个值的长度 showToast类似于JS中的alert,弹出框,title  是弹出框的显示的信息,icon是弹出框的图标状态,目前

只有loading 和success这两个状态。duration是弹出框在屏幕上显示的时间。 


重点来了

wx.request({
url: 'https://www.xxxxx.com/wx/form.php',
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST",
data: { xingming: e.detail.value.xingming, xingbie: e.detail.value.xingbie, aihao: e.detail.value.aihao },
success: function (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
})
}
}
})

wx.request({})是小程序发起https请求,注意http是不行的。

这里

A.url是你请求的网址,比如以前在前端,POST表单中action=‘index.php',这里的index.php是相对路径,而小程序

请求的网址必须是网络绝对路径。比如:https://www.xxxxxcom/wx/form.php

B.

header: {
 "Content-Type": "application/x-www-form-urlencoded"
 },

由于POST和GET传送数据的方式不一样,POST的header必须是

"Content-Type": "application/x-www-form-urlencoded"
GET的header可以是 'Accept': 'application/json'

C.一定要写明method:“POST”  默认是“GET”,保持大写

data:{xingming:e.detail.value.xingming,xingbie:e.detail.value.xingbie,aihao:e.detail.value.aihao},
 这里的data就是POST给服务器端的数据 以{name:value}的形式传送

D.成功回调函数

success: function (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
})
}
}

E.success:function()是请求状态成功触发是事件,也就是200的时候,注意,请求成功不是操作成功,请求只是这个程序到服务器端这条线的通的。

F. 

if (res.data.status == 0) {
wx.showToast({
title: '提交失败!!!',
icon: 'loading',
duration: 1500
})
}

加一条,单独写的事件也是也可的。具体问题具体对待

  saveEvaluate:function (e){
    let that = this;
    let answerPaths = this.data.listData.studentQuestionList[this.data.m].answerPaths;
    let studentId = this.data.listData.studentQuestionList[this.data.m].studentId;
    request.post({
      url: 接口名称,
      data: {
        photoId: this.data.detail.homeworkId,
        userId: studentId,
        photoRemark: e.detail.value.photoRemark,
        photoScore: e.detail.value.photoScore,
        answerPaths: answerPaths,
        access_token: app.getToken()
      }
    }).then(res => {
      if (res.data.code == 200) {
        that.setData({
          studentList: that.data.studentList,
          completeStudentList: that.data.completeStudentList
        })
        //刷新弹框页面数据
        wx.navigateTo({
          url: '/pages/xxx/xxx/xxx',
        })
      }
    })
  }


数据库表如下:

222.jpg


form.php文件

<?php
$con=mysqli_connect("localhost","root","root","DBname"); 
if (!$con)
  {
  die('Could not connect: ' . mysqli_connect_error());
  }
mysqli_query($con,"set names utf8");
if (!empty($_POST['xingming'])&&!empty($_POST['xingbie'])&&!empty($_POST['aihao'])){
$sql="INSERT INTO person (xingming, xingbie, aihao) VALUES ('$_POST[xingming]','$_POST[xingbie]','$_POST[aihao]')";
$result = mysqli_query($con,$sql);
if (!$result)
  {  
die('Error: ' . mysqli_connect_error());
}
 
}
 
$sql1 = "SELECT * FROM person";
$result1 = mysqli_query($con,$sql1);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
 
<title>表单</title>
</head>
 
<body style="margin:50px;">
 
<script language="JavaScript"> 
function myrefresh() 
{ 
window.location.reload(); 
} 
setTimeout('myrefresh()',10000); //指定1秒刷新一次 
</script> 
 
<table style='text-align:left;' border='1'>
         <tr><th>id</th><th>名字</th><th>性别</th><th>爱好</th></tr>
<?php
     while ($bookInfo = mysqli_fetch_array($result1,MYSQLI_ASSOC)){ //返回查询结果到数组
$xingming = $bookInfo["xingming"]; //将数据从数组取出
$xingbie = $bookInfo["xingbie"];
$aihao = $bookInfo["aihao"];
$id = $bookInfo["id"];
     echo "<tr><td>{$id}</td><td>{$xingming}</td><td>{$xingbie}</td><td>{$aihao}</td></tr>";
}
 
//释放结果集
mysqli_free_result($result1);
 
mysqli_close($con);
?>
</table>
 
</body>
</html>


原文地址:https://blog.csdn.net/wydd7522/article/details/80724526

转载请注明: ITTXX.CN--分享互联网 » 微信小程序form表单提交到MYSQL实例(PHP)

最后更新:2019-02-13 16:56:20

赞 (5) or 分享 ()
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽