因为刚学习php,所以对php并熟悉,很多地方其实可以优化或者可以把所有接口封装成一个接口调用,这个项目本意是学习通过php写增删改查接口,实现功能,前端页面只简单写了布局,所以请原谅前端页面只能将就的显示数据而已,文章底部附项目的下载地址。进入正题吧
数据库是我通过Navicat Premium 12快速创建的,数据库命名为articles,然后再创建一张表article。需要添加6个字段,分别是id(id作为主键需要自增长),title,auther,description,content,dateline保存各项数据
$servername = "localhost";
$username = "root";
$password = "123456";
?>
require_once('config.php');
$dbname = "articles";
//连接数据库
$con = new mysqli($servername, $username, $password, $dbname);
if($con->connect_error){
die('连接失败');
}
?>
3.接下来分别写增删改查4个接口,创建articleList.php文件,用于获取文章列表数据
//连接数据库
$action = $_GET['action'];
if($action == 'getList'){
require_once('connect.php');
$getInfoSql = "SELECT * FROM article order by id ASC";
$result = $con->query($getInfoSql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
$json = json_encode(array(
"resultCode"=>200,
"message"=>"查询成功!",
"data"=>$data
),JSON_UNESCAPED_UNICODE);
//转换成字符串JSON
echo($json);
}else{
$json = json_encode(array(
"resultCode"=>200,
"message"=>"暂无数据",
"data"=>''
),JSON_UNESCAPED_UNICODE);
//转换成字符串JSON
echo($json);
}
}
?>
$action = $_POST['action'];
if($action == 'add'){
//连接数据库
require_once('connect.php');
// //获取前端的数据
$title = $_POST['title'];
$auther = $_POST['authod'];
$description = $_POST['description'];
$content = $_POST['content'];
//获取当前的时间
$dateTime = date('Y-m-d h:i:s',time());
// 把数据写入数据库
$addSql = "INSERT INTO article(title,auther,description,content,dateline) VALUES ('$title','$auther','$description','$content','$dateTime')";
if ($con->query($addSql) === TRUE) {
$json = json_encode(array(
"resultCode"=>200,
"message"=>"添加成功!",
"data"=>[]
),JSON_UNESCAPED_UNICODE);
echo $json;
} else {
echo "Error: " . $addSql . "
" . mysqli_error($con);
}
}
?>
$action = $_POST['action'];
if($action == 'fixInfo'){
//连接数据库
require_once('connect.php');
// //获取前端的数据
$itemID = $_POST['id'];
$title = $_POST['title'];
$authod = $_POST['authod'];
$description = $_POST['description'];
$content = $_POST['content'];
$update = "UPDATE article SET title='$title',auther='$authod',description='$description',content='$content' WHERE id=$itemID ";
$result = $con->query($update);
if ($con->query($update) === TRUE) {
} else {
echo "Error: " . $update . "
" . mysqli_error($con);
}
$json = json_encode(array(
"resultCode"=>200,
"message"=>"更新成功!",
"data"=>[]
),JSON_UNESCAPED_UNICODE);
//转换成字符串JSON
echo($json);
}
?>
$action = $_POST['action'];
if($action == 'deleteItem'){
//连接数据库
require_once('connect.php');
// //获取前端的数据
$itemID = $_POST['id'];
// 把数据写入数据库
$deleteSql = "DELETE FROM article WHERE id = $itemID";
if ($con->query($deleteSql) === TRUE) {
$json = json_encode(array(
"resultCode"=>200,
"message"=>"删除成功!",
"data"=>[]
),JSON_UNESCAPED_UNICODE);
echo $json;
} else {
echo "Error: " . $deleteSql . "
" . mysqli_error($con);
}
}
?>
$action = $_POST['action'];
if($action == 'check'){
//连接数据库
require_once('connect.php');
// //获取前端的数据
$itemID = $_POST['id'];
// 把数据写入数据库
$checkSql = "SELECT * FROM article WHERE id=$itemID";
$result = $con->query($checkSql);
// print_r($result);
if($result->num_rows){
$data[] = $result->fetch_assoc();
};
$json = json_encode(array(
"resultCode"=>200,
"message"=>"查询成功!",
"data"=>$data
),JSON_UNESCAPED_UNICODE);
//转换成字符串JSON
echo($json);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文章列表</title>
</head>
<script src="js/jquery-1.12.4.js"></script>
<body>
<button id='addBtn' style='width: 80px;height: 30px;margin: 10px' >增加文章</button>
<table id="tableBox" border='1' width="800">
</table>
</body>
<script type="text/javascript">
$(function(){
getList();
function getList(){
$.ajax({
type: "get",
url:'articleList.php',
data:{
action:'getList'
},
dataType:'JSON',
success:(data)=>{
let tableInfo = data.data;
$('#tableBox').html('');
$('#tableBox').html('id 标题 作者 描述 内容 时间 操作 ');
tableInfo.forEach((item,index)=>{
let info = `<tr><td>${item.id}</td><td>${item.title}</td><td>${item.auther}</td><td>${item.description}</td><td>${item.content}</td><td>${item.dateline}</td><td><button id='checkBtn' myIndex='${index}'>查看</button> <button id='delete' myIndex='${index}'>删除</button> <button id="fixBtn" myIndex='${index}'>修改</button> </td></tr>`
$('#tableBox').append(info);
})
},
error:(e)=>{
console.log(e);
}
})
}
//删除按钮
$(document).on("click","#delete",function () {
let index = Number($(this).attr('myIndex'))+1;
let id = $(`tr:eq(${index})`)[0].children[0].innerText
deleteData(id);
});
//增加按钮
$(document).on('click','#addBtn',function(){
window.location.href = 'addArticle.html';
});
//查看按钮
$(document).on('click','#checkBtn',function(){
let index = Number($(this).attr('myIndex'))+1;
let id = $(`tr:eq(${index})`)[0].children[0].innerText
window.location.href = `checkArticle.html?id=${id}`;
});
//修改按钮
$(document).on('click','#fixBtn',function(){
let index = Number($(this).attr('myIndex'))+1;
let id = $(`tr:eq(${index})`)[0].children[0].innerText
window.location.href = `fixArticle.html?id=${id}`;
});
function deleteData(itemId){
$.ajax({
type:'post',
url:'delete.php',
data:{
action:'deleteItem',
id:itemId
},
dataType:'JSON',
success:(data)=>{
getList();
alert('删除成功');
},
error:(e)=>{
alert('删除失败');
}
})
}
})
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文章修改</title>
</head>
<script src="js/jquery-1.12.4.js"></script>
<style type="text/css">
.box{
text-align: center;
}
</style>
<body>
<table border="1">
<tr>
<td align="center" colspan='2' height='50'>修改文章</td>
</tr>
<tr>
<td align="center">标题:</td>
<td ><input type="text" name="title"></td>
</tr>
<tr>
<td align="center">作者:</td>
<td ><input type="text" name="authod" ></td>
</tr>
<tr>
<td align="center">简介:</td>
<td ><textarea cols="100" rows="10" name="description" id="description" ></textarea></td>
</tr>
<tr>
<td align="center">内容:</td>
<td ><textarea cols="100" rows="10" name="content" id="content" ></textarea></td>
</tr>
<tr>
<td><input id="btn" type="submit" name="submit" value="修改" align="center"></td>
</tr>
</table>
</body>
<script type="text/javascript">
$(function(){
function getUrlParam(name) {
// 用该属性获取页面 URL 地址从问号 (?) 开始的 URL(查询部分)
var url = window.location.search;
// 正则筛选地址栏
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
// 匹配目标参数
var result = url.substr(1).match(reg);
//返回参数值
return result ? decodeURIComponent(result[2]) : null;
}
let articleId = getUrlParam("id");
$.ajax({
type:'post',
url:'check.php',
data:{
action:'check',
id:articleId
},
dataType:'JSON',
success:(data)=>{
let articleData = data.data[0];
$("input[ name = 'title']").val(articleData.title);
$("input[ name = 'authod']").val(articleData.auther);
$(" textarea[ name='description' ] ").val(articleData.description);
$(" textarea[ name='content' ] ").val(articleData.content);
},
error:(e)=>{
console.log(e);
}
});
$(document).on('click','#btn',()=>{
let title = $("input[ name = 'title']").val();
let authod = $("input[ name = 'authod']").val();
let description = $("textarea[ name = 'description']").val();
let content = $("textarea[ name = 'content']").val();
fixData(articleId,title,authod,description,content);
})
function fixData(id,title,authod,description,content){
$.ajax({
type:'post',
url:'fix.php',
data:{
action:'fixInfo',
id:id,
title:title,
authod:authod,
description:description,
content:content,
},
dataType:'JSON',
success:(data)=>{
alert('更新成功');
$(window).attr('location','articleList.html');
},
error:(e)=>{
alert('失败');
}
})
}
});
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文章查看</title>
</head>
<script src="js/jquery-1.12.4.js"></script>
<style type="text/css">
.box{
text-align: center;
}
</style>
<body>
<div class='box'></div>
</body>
<script type="text/javascript">
$(function(){
function getUrlParam(name) {
// 用该属性获取页面 URL 地址从问号 (?) 开始的 URL(查询部分)
var url = window.location.search;
// 正则筛选地址栏
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
// 匹配目标参数
var result = url.substr(1).match(reg);
//返回参数值
return result ? decodeURIComponent(result[2]) : null;
}
let articleId = getUrlParam("id");
$.ajax({
type:'post',
url:'check.php',
data:{
action:'check',
id:articleId
},
dataType:'JSON',
success:(data)=>{
let articleData = data.data[0];
let info = `<h2>标题:${articleData.title}</h1><h2>作者:${articleData.auther} </h2><h3>时间:${articleData.dateline} </h3><h4>描述:${articleData.description}</h4><p>内容:${articleData.content}</p>`
$('.box').append(info);
},
error:(e)=>{
console.log(e);
}
})
})
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文章发布的界面</title>
</head>
<script src="js/jquery-1.12.4.js"></script>
<body>
<table border="1">
<tr>
<td align="center" colspan='2' height='50'>发布文章</td>
</tr>
<tr>
<td align="center">标题:</td>
<td ><input type="text" name="title"></td>
</tr>
<tr>
<td align="center">作者:</td>
<td ><input type="text" name="authod"></td>
</tr>
<tr>
<td align="center">简介:</td>
<td ><textarea cols="100" rows="10" name="description" id="description"></textarea></td>
</tr>
<tr>
<td align="center">内容:</td>
<td ><textarea cols="100" rows="10" name="content" id="content"></textarea></td>
</tr>
<tr>
<td><input id="btn" type="submit" name="submit" value="提交文章" align="center"></td>
</tr>
</table>
</body>
<script type="text/javascript">
$(function(){
$('#btn').click(()=>{
// alert($(" input[ name='title' ] ").val());
let title = $(" input[ name='title' ] ").val();
let authod = $(" input[ name='authod' ] ").val();
let description = $(" textarea[ name='description' ] ").val();
let content = $(" textarea[ name='content' ] ").val();
$.ajax({
type:'post',
url:'addArticle.php',
data:{
action:'add',
title:title,
authod:authod,
description:description,
content:content,
},
dataType:'JSON',
success:(data)=>{
alert('添加文章成功');
$(window).attr('location','articleList.html');
},
error:(e)=>{
console.log(e);
},
})
})
})
</script>
</html>
GitHub:https://github.com/xiaoyaoFreedom/Article