44使用php实现简单的前后端操作
一、准备
- 下载bootstrap并使用
- 下载phpstudy
- 下载mysql + Apache + php
二、存放路径
目录存放 (ctj文件夹下)
css文件夹、js文件夹、php文件夹、index.html文件
css文件夹下
bootstrap.min.css文件
js文件夹下
axios.ajax.js文件、js/jquery-2.2.4.js文件、bootstrap.js文件、index.js文件
php文件夹下
index.php文件、mysql.php文件
三、错题集的实现
结构
需要的模态框、按钮、表格都可以在bootstrap中拿到直接使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 引入css样式 -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- 引入js文件 -->
<script src="js/jquery-2.2.4.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<!-- 容器 -->
<div class="container" style="position: relative;">
<!-- 添加 按钮 -->
<button type="button" class="btn btn-primary" onclick="addBtn()">添加</button>
<!-- 表格 -->
<table class="table table-bordered table-hover" style="table-layout: fixed;" onclick="trust()">
<thead>
<tr>
<th>#</th>
<th>标题</th>
<th>位置</th>
<th>想法</th>
<th>操作</th>
</tr>
</thead>
<tbody></tbody>
</table>
<!-- 分页 -->
<nav aria-label="Page navigation" style="position:absolute;right:15px;">
<ul class="pagination"></ul>
</nav>
<!-- 点击 添加 按钮打开的模态框 -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">添加</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="control-label">标题:</label>
<input type="text" class="form-control" id="title">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">位置:</label>
<input type="text" class="form-control" id="pos">
</div>
<div class="form-group">
<label for="message-text" class="control-label">想法:</label>
<textarea class="form-control" id="idea" style="resize: none;"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" onclick="addSure()">保存</button>
</div>
</div>
</div>
</div>
</div>
<!-- 点击 修改 按钮打开的模态框 -->
<div class="modal fade" id="updModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"
onclick="updCancel()">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">修改</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="control-label">标题:</label>
<input type="text" class="form-control" id="title">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">位置:</label>
<input type="text" class="form-control" id="pos">
</div>
<div class="form-group">
<label for="message-text" class="control-label">想法:</label>
<textarea class="form-control" id="idea" style="resize: none;"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="updCancel()">取消</button>
<button type="button" class="btn btn-primary" onclick="updSure()">确定</button>
</div>
</div>
</div>
</div>
<!-- 点击 删除 按钮打开的模态框 -->
<div class="modal fade" tabindex="-1" role="dialog" id="delModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"
onclick="delCancel()">×</span></button>
<h4 class=" modal-title">删除</h4>
</div>
<div class="modal-body">
<p>确定要删除吗?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="delCancel()">取消</button>
<button type="button" class="btn btn-primary" onclick="delSure()" id="sure">确定</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- 引入js文件 -->
<script src="js/axiois.js"></script>
<script src="js/index.js"></script>
</body>
</html>
JavaScript
之前封装的axios函数如下
class Axios {
static ajax(item = {}) {
let {
url,
data,
method
} = item
if (!url) {
throw new Error('输入地址')
}
let arr = []
for (let i in data) {
arr.push(`${i}=${data[i]}`)
}
data = arr.join("&")
return new Promise((resolve, reject) => {
let http = new XMLHttpRequest()
if (method == "get") {
url = url + "?" + data
data = ""
}
http.open(method, url, true)
http.setRequestHeader("content-type", "application/x-www-form-urlencoded")
http.send(data)
http.onreadystatechange = function () {
if (http.readyState == 4) {
if (http.status == 200) {
let res = JSON.parse(http.response)
resolve(res)
} else {
reject(http.status)
}
}
}
})
}
}
实现主要功能的index.js如下
// 点击添加事件触发事情
function addBtn(){
$('#addModal').modal('show')
}
// 获取节点函数
function getNode(css){
return document.querySelector(css)
}
// 添加模态框点击保存触发的事件
function addSure(){
// 获取模态框表单的值
let title = getNode("#addModal #title").value
let pos = getNode("#addModal #pos").value
let idea = getNode("#addModal #idea").value
//判断模态框表单的值是否为空,为空则不继续执行
if(!title || !pos || !idea) return
// 存储数据
let obj = {
url : "php/index.php",
data : {
fn : "add",
title,
pos,
idea
},
method : "post"
}
// 调用封装的axios函数
Axios.ajax(obj).then(data => {
// 成功后关闭模态框
$('#addModal').modal('hide')
// 刷新页面
location.reload()
}).catch(data => {
// 失败后打印错误
console.log(data)
})
}
// 自动展示当前页的数据库数据
// 默认当前页面pageNum=1
function showData(pageNum = 1) {
// 存储数据
let obj = {
url : "php/index.php",
data : {
fn : "get",
pageNum
},
method : "post"
}
//调用封装的axios函数
Axios.ajax(obj).then(data => {
// 成功后
// 获取分页的的节点
let ul = getNode("nav ul")
// 每次调用就清空ul里面的页码
ul.innerHTML = ""
//对总页码进行遍历创建页码
for(let i = 1; i <= data.sumPageNum; i++){
// 页码添加到ul中
let li = `<li ${pageNum == i && 'class="active"'}><a href="#" οnclick="swapPage(${i})">${i}</a></li>`
ul.innerHTML += li
}
// 获取表格的表格体tbody
let tbody = getNode("table tbody")
// 设置常量upd和del两个按钮
const upd = `<button type="button" class="btn btn-success btn-xs" id="upd">修改</button> `
const del = `<button type="button" class="btn btn-danger btn-xs" id="del">删除</button>`
// 每次调用就清空tbody里面的数据
tbody.innerText = ""
// 对数据进行遍历
data.data.forEach(item => {
// 创建tr
let tr = document.createElement("tr")
// 对每个对象进行遍历
for(let attr in item) {
// 创建td
let td = document.createElement("td")
// 将每个值分别存入td中
td.innerText = `${item[attr]}`
// 再将td追加到填入中
tr.appendChild(td)
}
// 将两个按钮追加到tr中
let handle = document.createElement("td")
handle.innerHTML = upd + del
tr.appendChild(handle)
// 最后将每个tr追加到tbody中
tbody.appendChild(tr)
})
}).catch(data => {
// 失败后打印错误
console.log(data)
})
}
// 自动调用展示函数
showData()
// 点击页码触发的事件
function swapPage(pageNum){
// 调用展示函数,将展示函数的默认函数重新赋值
showData(pageNum)
}
// 使用委派事件完成删除和修改功能
function trust(e){
e = e || window.event
let tar = e.target
if(tar.id == "upd"){
// 如果点击的按钮时修改按钮就调用upd函数
upd(tar)
}else if(tar.id == "del"){
// 如果点击的按钮时删除按钮就调用del函数
del(tar)
}
}
// 修改函数
function upd(tar){
// 打开修改模态框
$('#updModal').modal('show')
// 获取需要删除的一项的值
let id = tar.parentNode.parentNode.children[0].innerText
let title = tar.parentNode.parentNode.children[1].innerText
let pos = tar.parentNode.parentNode.children[2].innerText
let idea = tar.parentNode.parentNode.children[3].innerText
// 将原来的值放在修改模态框中
let form = getNode("#updModal form")
getNode("#updModal #title").value = title
getNode("#updModal #pos").value = pos
getNode("#updModal #idea").value = idea
// 创建一个隐藏表单,用于存储需要删除的一项的id
let input = document.createElement("input")
input.type = "hidden"
input.id = id
form.appendChild(input)
}
// 点击修改模态框的确定时触发的事件
function updSure(){
// 获取修改模态框表单的值
let title = getNode("#updModal #title").value
let pos = getNode("#updModal #pos").value
let idea = getNode("#updModal #idea").value
let id = getNode("#updModal input[type='hidden']").id
// 如果修改模态框表单值有空就停止
if(!title || !pos || !idea) return
// 存储数据
let obj = {
url : "php/index.php",
data : {
fn : "upd",
id,
title,
pos,
idea
},
method : "post"
}
// 调用封装的axios函数
Axios.ajax(obj).then(data => {
// 成功后删除添加的隐藏表单,关闭修改模态框并刷新页面
updCancel()
$('#updModal').modal('hide')
location.reload()
})
}
// 点击修改模态框的取消或x触发或修改成功后触发的事件
function updCancel(){
// 将创建的表单隐藏域删除
getNode("#updModal input[type='hidden']").remove()
}
// 删除函数
function del(tar){
// 打开删除模态框
$('#delModal').modal('show')
// 获取需要删除项的id
let id = tar.parentNode.parentNode.children[0].innerText
// 获取确定按钮
let sure = getNode("#delModal #sure")
// 给确定按钮设置自定标签存储id
sure.setAttribute("index", id)
}
// 点击删除模态框确定触发的事件
function delSure(){
// 获取确定按钮
let sure = getNode("#delModal #sure")
// 获取确定按钮的自定义标签上的id
let id = sure.getAttribute("index")
// 存储数据
let obj = {
url : "php/index.php",
data : {
fn : "del",
id
},
method : "post"
}
// 调用封装的axios函数
Axios.ajax(obj).then(data => {
// 成功后刷新页面
location.reload()
}).catch(data => {
// 失败后打印错误
console.log(data)
})
}
// 点击模态框的取消或x触发的事件
function delCancel(){
// 获取确定按钮并删除自定义标签
let sure = getNode("#delModal #sure")
sure.removeAttribute("index")
}
php
连接数据库
<?php
function con(){
$link = mysqli_connect('127.0.0.1','root','root','test',3306);
if(!$link){
echo '连接失败';
die;
}
return $link;
}
// 执行非查询操作
function query($sql){
$link = con();
$res = mysqli_query($link,$sql);
return $res;
}
// 执行查询操作的
function select($sql){
$link = con();
$res = mysqli_query($link,$sql);
if(!$res){
return false;
}
$arr = [];
while($tmp = mysqli_fetch_assoc($res)){
$arr[]= $tmp;
}
return $arr;
}
?>
实现后端调用数据库功能
<?php
// 引入mysql文件
include('mysql.php');
// 获取访问的方法
$fn = $_POST['fn'];
// add()
$fn();
// 添加数据的方法
function add(){
// echo 222;
$title = $_POST['title'];
$pos = $_POST['pos'];
$idea = $_POST['idea'];
$sql = "insert into problem1 values(null,'$title','$pos','$idea')";
$res = query($sql);
echo $res;
}
// 获取数据的方法
function get(){
$length = 5;
$pageNum = $_POST["pageNum"];
$sql1 = "select count(id) as dataNum from problem1";
$dataNum = select($sql1);
$dataNum = $dataNum[0]["dataNum"];
$sumPageNum = ceil($dataNum/$length);
$start = ($pageNum - 1) * $length;
$sql = "select * from problem1 order by id limit $start,$length";
$res = select($sql);
$res = [
'sumPageNum'=>$sumPageNum,
'data'=>$res
];
print_r(json_encode($res));
}
// 删除数据的方法
function del(){
$id = $_POST['id'];
$sql = "delete from problem1 where id=$id";
$res = query($sql);
echo $res;
}
// 修改数据的方法
function upd(){
$idea = $_POST['idea'];
$title = $_POST['title'];
$pos = $_POST['pos'];
$id = $_POST['id'];
$sql = "update problem1 set title='$title',pos='$pos',idea='$idea' where id=$id";
$res = query($sql);
echo $res;
}
?>
mysql
在mysql中创建数据库以及说明数据类型
create table problem1(
id int primary key auto_increment,
title varchar(20) not null comment '标题',
pos varchar(20) not null comment '位置',
idea varchar(20) not null comment '想法'
)engine=MyISAM default charset=utf8;