Vue.js/PHP/MySQL增删改查CRUD示例代码

Vue.js/PHP/MySQL增删改查CRUD示例代码

运行环境:php + mysql+ apache/nginx + php-fpm

一 准备数据库

创建数据库vue,数据表 users,下面是表结构(此处配置涉及相关文件修改,后面具体文件中会提及)

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `mobile` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

二 准备运行环境

笔者的存放目录是vuecrud,访问地址是:http://localhost/vuecrud/(此处配置涉及相关文件修改,后面具体文件中会提及)

三 程序文件

入口文件 index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>VueJS CRUD project By KK</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
	<link rel="stylesheet" href="style.css">
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
</head>
<body>


	<div id="root">

		<div class="">
			<div class="crud_header">
				<h1 class="left">VueJS CRUD WITH PHP AND MySQL</h1>
				<button class="right addnew" @click="showingModal = true;">Add New</button>
				<div class="fix"></div>
			</div>
			
			<hr>
			<p class="errorMessage" v-if="errorMessage">{{errorMessage}}</p>
			<p class="successMessage" v-if="successMessage">{{successMessage}}</p>

			<table class="list">
				<tr>
					<th>ID</th>
					<th>Username</th>
					<th>Email</th>
					<th>Phone Number</th>
					<th>Edit</th>
					<th>Delete</th>
				</tr>
				<tr v-for="user in users">
					<td>{{user.id}}</td>
					<td>{{user.username}}</td>
					<td>{{user.email}}</td>
					<td>{{user.mobile}}</td>
					<td><button @click="showingeditModal = true; selectUser(user)">Edit</button></td>
					<td><button @click="showingdeleteModal = true; selectUser(user)" >Delete</button></td>
				</tr>
			</table>
			<div class="fix"></div>
			<div class="modal col-md-6" id="addmodal" v-if="showingModal">
				<div class="modalheading">
					<p class="left">Add new user</p>
					<p class="right close" @click="showingModal = false;">x</p>
					<div class="fix"></div>
				</div>
				<div class="modalbody">
					<div class="modalcontent">
						<table class="form">
							<tr>
								<th>Usename</th>
								<th>:</th>
								<td><input type="text" placeholder="Usename" v-model="newUser.username"></td>
							</tr>
							<tr>
								<th>Email Adress</th>
								<th>:</th>
								<td><input type="email" placeholder="Email" v-model="newUser.email"></td>
							</tr>
							<tr>
								<th>Phone Number</th>
								<th>:</th>
								<td><input type="text" placeholder="Phone" v-model="newUser.mobile"></td>
							</tr>
						</table>
						<div class="margin"></div>
						<button class="center"  @click="showingModal = false; saveUser();" >Add User</button>
					</div>
				</div>
			</div>
		<div class="modal col-md-6" id="editmodal" v-if="showingeditModal">
				<div class="modalheading">
					<p class="left">Edit user</p>
					<p class="right close" @click="showingeditModal = false;">x</p>
					<div class="fix"></div>
				</div>
				<div class="modalbody">
					<div class="modalcontent">
						<table class="form">
							<tr>
								<th>Usename</th>
								<th>:</th>
								<td><input type="text" placeholder="Username" v-model="clickedUser.username"></td>
							</tr>
							<tr>
								<th>Email Adress</th>
								<th>:</th>
								<td><input type="email" placeholder="Email Adress" v-model="clickedUser.email"></td>
							</tr>
							<tr>
								<th>Phone Number</th>
								<th>:</th>
								<td><input type="text" placeholder="Phone Number"  v-model="clickedUser.mobile"></td>
							</tr>
						</table>
						<div class="margin"></div>
						<button class="center"  @click="showingeditModal = false; updateUser()">Update User</button>
					</div>
				</div>
			</div>
			<div class="modal col-md-6" id="deletemodal" v-if="showingdeleteModal">
				<div class="modalheading">
					<p class="left">Delete user</p>
					<p class="right close" @click="showingdeleteModal = false;">x</p>
					<div class="fix"></div>
				</div>
				<div class="modalbody">
					<div class="modalcontent">
						
						<div class="margin"></div>
						<h3 class="center">Are you sure to Delete?</h3>
						<div class="margin"></div>
						<h4 class="center">{{clickedUser.username}}</h4>
						<div class="margin"></div>
						<div class="col-md-6 center">
							<button class="left" @click="showingdeleteModal = false; deleteUser()">YES</button>
							<button class="right" @click="showingdeleteModal = false;">NO</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
	<script type="text/javascript" src="app.js"></script>
	

</body>
</html>

样式文件 style.css

*{
	margin: 0;
	padding: 0;
}
body {
    margin: 0;
    font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #212529;
    text-align: left;
    background-color: #e0e0e0;
}
.left{
	float: left;
	display: block;
	overflow: hidden;
}
.right{
	float: right;
}
.fix{
	overflow: hidden;
	clear: both;
}
h1{
	font-size: 25px;

}
button{
	padding: 0 15px;
	border: 0;
	background: #02a2ff;
	color: #fff;
	border-radius: 3px;
	cursor: pointer;
	outline: 0;
}
div#root {
    margin-top: 50px;
    background: #f3f3f3;
    padding: 50px;
}
table.list{
	width:100%;

}
table.list tr{
	
margin: 5px!important;
	
border: 1px solid #fff;
}
table.list th {
    background: #02a2ff;
    padding: 2px;
    text-align: center;
}
.crud_header {
    background: #e0e0e0;
    padding: 35px 22px 20px 20px;
}
table.list tr td{
	
padding: 10px;
	
margin: 2px!important;
	
background: #ddd;
	
overflow: hidden;
	
text-align: center;
	
margin-top: 5px;
	
border-right: 1px solid #fff;
}
.modal{
	top: 99px;
	left:0;
	right:0;
	bottom:0;
	position: fixed;
	background: #b5b5b5fc;
	margin: 0 auto;
	display: block;
	padding: 0;
	height: 300px;
	box-shadow: 0 0 130px 28px #00000073;
}
.modalheading{
	background: #fff;
	padding: 5px;
	font-size: 17px;
	line-height: 32px;
}
.modalcontent {
    padding: 10px;
}
table.form {
    width: 100%;
}
.form tr{
text-align: center;
border-bottom: 5px solid #b6b6b6;
}
.form td{
text-align: left;
margin: 0 10px;
border: 5px solid #b6b6b6;
}
.form th{
	
text-align: right;
	
border-right: 5px solid #b6b6b6;
}
.margin{
	margin: 30px 0;
}
.center {
    text-align: center;
    display: block;
    margin: 0 auto;
}
p.errorMessage {
    background: #ffbaba;
    padding: 10px;
    border-left: 5px solid #f00;
}
p.successMessage {
    background: #a2ffa2;
    padding: 10px;
    border-left: 5px solid #008c1e;
}
.form td input {
    padding:5px 10px;
    outline: 0;
}

JS核心文件 app.js

此处需要注意php后端api数据请求的地址。

var app = new Vue({

	el: "#root",
	data: {
		showingModal:false,
		showingeditModal: false,
		showingdeleteModal: false,
		errorMessage : "",
		successMessage : "",
		users: [],
		newUser: {username: "", email: "", mobile: ""},
		clickedUser: {},
		
	},
	mounted: function () {
		console.log("Hi KK");
		this.getAllUsers();
	},
	methods: {
		getAllUsers: function(){
			axios.get("http://localhost/vuecrud/api.php?action=read")
			.then(function(response){
				console.log(response);
				if (response.data.error) {
					app.errorMessage = response.data.message;
				}else{
					app.users = response.data.users;
				}
			});
		},
		saveUser:function(){

			var formData = app.toFormData(app.newUser);
			axios.post("http://localhost/vuecrud/api.php?action=create", formData)
				.then(function(response){
					console.log(response);
					app.newUser = {username: "", email: "", mobile: ""};
					if (response.data.error) {
						app.errorMessage = response.data.message;
					}else{
						app.successMessage = response.data.message;
						app.getAllUsers();
					}
				});
			},
			updateUser:function(){

			var formData = app.toFormData(app.clickedUser);
			axios.post("http://localhost/vuecrud/api.php?action=update", formData)
				.then(function(response){
					console.log(response);
					app.clickedUser = {};
					if (response.data.error) {
						app.errorMessage = response.data.message;
					}else{
						app.successMessage = response.data.message;
						app.getAllUsers();
					}
				});
			},
			deleteUser:function(){

			var formData = app.toFormData(app.clickedUser);
			axios.post("http://localhost/vuecrud/api.php?action=delete", formData)
				.then(function(response){
					console.log(response);
					app.clickedUser = {};
					if (response.data.error) {
						app.errorMessage = response.data.message;
					}else{
						app.successMessage = response.data.message;
						app.getAllUsers();
					}
				});
			},
			selectUser(user){
				app.clickedUser = user;
			},

			toFormData: function(obj){
				var form_data = new FormData();
			      for ( var key in obj ) {
			          form_data.append(key, obj[key]);
			      } 
			      return form_data;
			},
			clearMessage: function(){
				app.errorMessage = "";
				app.successMessage = "";
			},
		
	}
});

php后端Api文件 api.php

此处需要注意配置数据库连接地址,用户名,密码,数据库名,数据表名等相关事项。

<?php 

$conn = new mysqli("localhost", "root", "kinglife", "vue");
if ($conn->connect_error) {
	die("Database connection established Failed..");
} 
$res = array('error' => false);



$action = 'read';

if (isset($_GET['action'])) {
	$action = $_GET['action'];
}

if ($action == 'read') {
	$result = $conn->query("SELECT * FROM `users`");
	$users = array();

	while ($row = $result->fetch_assoc()){
		array_push($users, $row);
	}
	$res['users'] = $users;
}

if ($action == 'create') {

	$username = $_POST['username'];
	$email = $_POST['email'];
	$mobile = $_POST['mobile'];


	$result = $conn->query("INSERT INTO `users` (`username`, `email`, `mobile`) VALUES ('$username', '$email', '$mobile') ");
	if ($result) {
		$res['message'] = "User Added successfully";
	} else{
		$res['error'] = true;
		$res['message'] = "Insert User fail";
	}
}


if ($action == 'update') {
	$id = $_POST['id'];
	$username = $_POST['username'];
	$email = $_POST['email'];
	$mobile = $_POST['mobile'];


	$result = $conn->query("UPDATE `users` SET `username` = '$username', `email` = '$email', `mobile` = '$mobile'WHERE `id` = '$id'");
	if ($result) {
		$res['message'] = "User Updated successfully";
	} else{
		$res['error'] = true;
		$res['message'] = "User Update failed";
	}
}





if ($action == 'delete') {
	$id = $_POST['id'];
	$username = $_POST['username'];
	$email = $_POST['email'];
	$mobile = $_POST['mobile'];


	$result = $conn->query("DELETE FROM `users` WHERE `id` = '$id'");
	if ($result) {
		$res['message'] = "User deleted successfully";
	} else{
		$res['error'] = true;
		$res['message'] = "User delete failed";
	}
}

$conn -> close();
header("Content-type: application/json");
echo json_encode($res);
die();

 ?>

REF:

Post Comment