php Vue编辑mysql ajax

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Vue编辑mysql ajax相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html>
	<head>
		<title>Vue Project</title>
		<meta http-equiv='content-type' content='text/html;charset=utf-8'>
		<meta name='viewport' content='width=device-width,initial-scale=1.0'>
		<style>
			*{padding:0;margin:0;list-style:none;font-size:24px;line-height:30px;font-family:helvetica;}
			#list li{margin:5px;padding:5px;background:#CCFFFF;border-radius:5px;}
			#list li b{color:#0000FF}
			#err_msg{margin:5px;padding:5px;background:#FF0033;border-radius:5px;color:white}
			#delete_item{font-size:16px;}
			#edit_item{font-size:16px;}
			#delete_item:hover{font-size:18px;}
			#edit_item:hover{font-size:18px;}
			#create_item{margin:5px;padding:5px;background:#00FFFF;border-radius:5px;}
			#create_item li{margin:10px;}
			#modal{
				position:fixed;z-index:999;width:100%;height:100%;left:0;top:0;
				background-color:rgba(0,0,0,0.6)
			}
			#modal_content{
				background:white;
				border:2px solid yellow; border-radius:5px;
				margin:10% auto;width:80%
			}
		</style>
		<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
  <body>
	<div id="app">
		<div id='modal' v-if='edit_switch'>
			<div id='modal_content'>
				<ul>
					<li>
						<span>Brand: </span>
						<input placeholder='please enter brand' v-model.trim='edited_item.brand'/>
					</li>
					<li>
						<span>Model: </span>
						<input placeholder='please enter model' v-model.trim='edited_item.model'/>
					</li>
					<li>
						<span>Engine: </span>
						<select v-model='edited_item.engine'>
							<option value='Petrol'>Petrol</option>
							<option value='Diesel'>Diesel</option>
							<option value='Electric'>Electric</option>
							<option value='Hybrid'>Hybrid</option>
							<option value='Hydrogen'>Hydrogen</option>
						</select>
					</li>
					<li>
						<span>Automatic: </span>
						<input type='radio' value='Automatic' v-model='edited_item.gearbox'/>
						<span>Manual: </span>
						<input type='radio' value='Manual' v-model='edited_item.gearbox'/>
					</li>
					<li><button v-bind:disabled='save_switch' @click='save_edit'>Save</button></li>
				</ul>
			</div>
		</div>
		<ul id='list' v-if='car_info_set.length'>
			<li v-for='element in car_info_set'>
				Brand is <b>{{element.brand}}</b>, model is <b>{{element.model}}</b>, 
				engine is <b>{{element.engine}}</b> and gearbox is <b>{{element.gearbox}}</b>.
				<span id='delete_item' @click = "delete_item(element.car_id)">[Delete]</span>
				<span id='edit_item' @click='start_edit(element)'>[Edit]</span>
			</li>
		</ul>
		<p id='err_msg' v-else>{{err_msg}}</p>
		<hr/>
		<ul id='create_item'>
			<li>
				<span>Brand: </span>
				<input placeholder='please enter brand' v-model.trim='new_item.brand'/>
			</li>
			<li>
				<span>Model: </span>
				<input placeholder='please enter model' v-model.trim='new_item.model'/>
			</li>
			<li>
				<span>Engine: </span>
				<select v-model='new_item.engine'>
					<option value='1'>Petrol</option>
					<option value='2'>Diesel</option>
					<option value='3'>Electric</option>
					<option value='4'>Hybrid</option>
					<option value='5'>Hydrogen</option>
				</select>
			</li>
			<li>
				<span>Automatic: </span>
				<input type='radio' value='1' v-model='new_item.gearbox'/>
				<span>Manual: </span>
				<input type='radio' value='2' v-model='new_item.gearbox'/>
			</li>
			<li>
				<button v-bind:disabled = 'btn_switch' @click='create_item'>Create</button>
			</li>
		</ul>
	</div>
	<script type='text/javascript'>	
		var vm = new Vue({
			el:'#app',
			data:{
				edit_switch:false,
				new_item:{brand:'',model:'',engine:'1',gearbox:'1',},
				car_info_set:[],
				err_msg:'Sorry, no car in record.',
				url:'./interface.php',
				edited_item:null,
			},
			computed:{
				btn_switch:function(){
					if(this.new_item.brand.length>=1&&this.new_item.model.length>=1){
						return false
					}else{
						return true
					}
				},
				save_switch:function(){
					if(this.edited_item.brand.length>=1&&this.edited_item.model.length>=1){
						return false
					}else{
						return true
					}
				},
			},
			created:function(){
				this.retrieve_all()
			},
			methods:{
				start_edit:function(element){
					this.edit_switch = true
					this.edited_item = element
				},
				save_edit:function(){
					this.edit_switch = false
					var self = this
					$.post({
						url:self.url,
						data:{
							action:'update_item',
							edited_item:self.edited_item
						}
					})
					.always(function(data){
						self.car_info_set = [] // compulsory
						self.err_msg = '' // optional
					})
					.done(function(data){
						var result = JSON.parse(data)
						if(result[0]){
							self.retrieve_all()
						}else{
							self.err_msg = result[1]
						}
					})
					.fail(function(data){
						self.err_msg = data.statusText
					})
				},
				create_item:function(){
					var self = this
					$.post({
						url:self.url,
						data:{
							action:'create_item',
							new_item:self.new_item
						}
					})
					.always(function(data){
						self.car_info_set = [] // compulsory
						self.err_msg = '' // optional
					})
					.done(function(data){
						var result = JSON.parse(data)
						if(result[0]){
							self.retrieve_all()
						}else{
							self.err_msg = result[1]
						}
					})
					.fail(function(data){
						self.err_msg = data.statusText
					})
				},
				retrieve_all:function(){
					var self = this
					$.ajax({
						url: self.url,
						method:'POST',
						data:{
							action:'retrieve_all'
						}
					})
					.always(function(data){
						self.car_info_set = [] // compulsory
						self.err_msg = '' // optional
					})
					.done(function(data){
						var result = JSON.parse(data)
						if(result[0]){
							self.car_info_set = result[1]
						}else{
							self.err_msg = result[1]
						}
					})
					.fail(function(data){
						self.err_msg = data.statusText
					})
				},
				delete_item:function(car_id){
					// send delete connand and car id to backend PHP file
					var self = this
					$.post({
						url:self.url,
						data:{
							action:'delete_item',
							car_id:car_id
						}
					})
					.always(function(data){
						self.car_info_set = [] // compulsory
						self.err_msg = '' // optional
					})
					.done(function(data){
						var result = JSON.parse(data)
						if(result[0]){
							self.retrieve_all()
						}else{
							self.err_msg = result[1]
						}
					})
					.fail(function(data){
						self.err_msg = data.statusText
					})
				}
			}
		})
		//setInterval(function(){vm.retrieve_all()},1000)
	</script>	
	</body>
</html>
















<?php
if(!empty($_POST['action'])){
	$db = @new MySQLi('localhost','root','','vue');
		if($db->connect_error){
			exit(json_encode([false,$db->connect_error]));
		}
	if($_POST['action']=='retrieve_all'){
		$sql = "SELECT `car_id`, `brand`, `model`, `engine`, `gearbox` FROM `car`";
		//$sql = "SELECT `car_id`, `brand`, `model`, `engine`, `gearbox` FROM `car` WHERE `brand`='Ferrari'";
		$result = $db->query($sql);
		if($result){
			if($result->num_rows==0){
				// no row retrieved
				echo json_encode([false,'no row retrieved']);
			}else{
				while($each_row = $result->fetch_assoc()){
					$all_rows[] = $each_row;
				}
				echo json_encode([true,$all_rows]);
			}
			$result->free();
		}else{
			// sql query error
			echo json_encode([false,'SQL Query Error']);
		}
		$db->close();
	}elseif($_POST['action']=='delete_item'){
		if(!empty($_POST['car_id'])){
			$_POST['car_id'] = $db->real_escape_string($_POST['car_id']);
			$sql = "DELETE FROM `car` WHERE `car_id` = '{$_POST['car_id']}' LIMIT 1";
			$result = $db->query($sql);
			if($result){
				echo json_encode([true,'delete successful']);
			}else{
				echo json_encode([false,'delete failure']);
			}
		}else{
			echo json_encode([false,'need car id to delete...']);
		}
		$db->close();
	}elseif($_POST['action']=='create_item'){
		// sanitizing data first
		if(!empty($_POST['new_item'])){
			if(!empty($_POST['new_item']['brand'])&&!empty($_POST['new_item']['model'])&&!empty($_POST['new_item']['engine'])&&!empty($_POST['new_item']['gearbox'])){
				// check brand, model, engine and gearbox
				// translate engine and gearbox code...
				$brand = $db->real_escape_string($_POST['new_item']['brand']);
				$model = $db->real_escape_string($_POST['new_item']['model']);
				$engine = $db->real_escape_string($_POST['new_item']['engine']);
				$gearbox = $db->real_escape_string($_POST['new_item']['gearbox']);
				switch($engine){
					case 1:
					$engine = "Petrol";
					break;
					case 2:
					$engine = "Diesel";
					break;
					case 3:
					$engine = "Electric";
					break;
					case 4:
					$engine = "Hybrid";
					break;
					case 5:
					$engine = "Hydrigen";
					break;
					default:
					$engine = false;
				}
				if($gearbox ==1){
					$gearbox = "Automatic";
				}elseif($gearbox ==2){
					$gearbox = "Manual";
				}else{
					$gearbox = false;
				}
				if($engine==false||$gearbox == false){
					echo json_encode([false,'illegal data...']);
				}else{
					$sql = "INSERT INTO `car` SET `brand`='{$brand}', `model`='{$model}', `engine`='{$engine}', `gearbox`='{$gearbox}' ";
					$result = $db->query($sql);
					if($result){
						echo json_encode([true,'new row created']);
					}else{
						echo json_encode([false,'SQL Error']);
					}
				}
				
			}else{
				echo json_encode([false,'insufficient data, cannot create new row...']);
			}
		}else{
			echo json_encode([false,'no data sent, cannot create new row...']);
		}
		$db->close();
	}elseif($_POST['action']=='update_item'){
		// update table row here
		// check to see if all five fields are here
		// then sanitize all five field values
		if(!empty($_POST['edited_item'])){
			if(!empty($_POST['edited_item']['car_id'])&&!empty($_POST['edited_item']['brand'])&&!empty($_POST['edited_item']['model'])&&!empty($_POST['edited_item']['engine'])&&!empty($_POST['edited_item']['gearbox'])){
				$car_id = $db->real_escape_string($_POST['edited_item']['car_id']);
				$brand = $db->real_escape_string($_POST['edited_item']['brand']);
				$model = $db->real_escape_string($_POST['edited_item']['model']);
				$engine = $db->real_escape_string($_POST['edited_item']['engine']);
				$gearbox = $db->real_escape_string($_POST['edited_item']['gearbox']);
				$sql = "UPDATE `car` SET `brand`='{$brand}', `model`='{$model}', `engine`='{$engine}', `gearbox`='{$gearbox}' WHERE `car_id`='{$car_id}' ";
				$result = $db->query($sql);
				if($result){
					echo json_encode([true,"successful update"]);
				}else{
					echo json_encode([false,'SQL ERROR, cannot update new row...']);
				}
			}else{
				echo json_encode([false,'insufficient data, cannot update new row...']);
			}
		}else{
			echo json_encode([false,'no data sent, cannot update new row...']);
		}
		$db->close();
	}
}




















?>

以上是关于php Vue编辑mysql ajax的主要内容,如果未能解决你的问题,请参考以下文章

内联可编辑行以使用 ajax php 更新数据库 mysql 中的每个记录

PHP / MySQL / AJAX - 更新多个数据

使用 Jquery、PHP、Mysql 进行 Ajax 分页 [关闭]

如何使用 bootstrap 和 Ajax 根据所选 ID 从 MySQL 数据库中获取数据?

无法从mysql db为summernote vue html编辑器赋值

使用 php jquery ajax 从 mysql 获取图像并将它们显示在 DIV 内的 html 页面中