본문 바로가기
PHP 박살내기/php ajax json

PHP 객체지향 방식으로 Mysql Ajax 조회 추가 수정 삭제

by 인생여희 2017. 9. 18.
반응형

PHP 객체지향 방식으로 Mysql Ajax 조회 추가 수정 삭제


#화면


#mysql



#경로



#index.php

<?php
//index.php
include 'crud.php';
$object = new Crud();
?>

<html>
<head>
<title>PHP 객체지향 방식으로 Mysql Ajax Crud </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
body
{
margin:0;
padding:0;
background-color:#f1f1f1;
}
.box
{
width:900px;
padding:20px;
background-color:#fff;
border:1px solid #ccc;
border-radius:5px;
margin-top:100px;
}
</style>
</head>
<body>
<div class="container box">
<h3 align="center">PHP 객체지향 방식으로 Mysql Ajax Crud</h3><br />
<br />

<button type="button" name="add" class="btn btn-success" data-toggle="collapse"
data-target="#user_collapse">추가</button>

</br></br>

<div id="user_collapse" class="collapse">
<form method="post" id="user_form">
<lable></label>
<input type="text" name="first_name" id="first_name" class="form-control" />
</br>

<lable>이름</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
</br>

<lable>이미지</label>
<input type="file" name="user_image" id="user_image" />
<input type="hidden" name="hidden_user_image" id="hidden_user_image" />
<span id="uploaded_image"></span>
</br>

<div align="center">
<input type="hidden" name="action" id="action" />
<input type="hidden" name="user_id" id="user_id" />
<input type="submit" name="button_action" id="button_action"
value="추가" />
</div>
</form>
</div>

<!-- 유저 정보 데이터 뿌려주는 곳 -->
<div id="user_table" class="table-responsive">
</div>
</div>
</body>
</html>

<script>
$(document).ready(function(){

load_data();
$('#action').val("Insert");

function load_data()
{
var action = "Load";
$.ajax({
url:"action.php",
method:"POST",
data:{action:action},
success:function(data){

$('#user_table').html(data);
}
});
}


$('#user_form').on('submit',function(event){

event.preventDefault();

var firstName = $('#first_name').val();
var lastName = $('#last_name').val();
var extension = $('#user_image').val().split('.').pop().toLowerCase();

if(extension !='')
{
if(jQuery.inArray(extension,['gif','png','jpg','jpeg'])== -1)
{
alert("지원되지 않는 파일 입니다.");
$('#user_image').val('');
return false;
}

}
if(firstName != '' && lastName !='')
{
$.ajax({
url:"action.php",
method:"POST",
data:new FormData(this),
contentType:false,
processData:false,
success:function(data){

alert(data);
$('#user_form')[0].reset();
load_data();
$("#action").val("Insert");
$('#button_action').val("추가");
$('#uploaded_image').html('');
}

});


}else
{
alert("빈칸이 있습니다");
}

});

//수정 버튼 클릭했을 때
$(document).on('click','.update',function(){
var user_id = $(this).attr("id");
var action = "Single";
$.ajax({
url:"action.php",
method:"POST",
data:{user_id:user_id,action:action},
dataType:"json",
success:function(data){

$('.collapse').collapse("show");
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#uploaded_image').html(data.image);
$('#hidden_user_image').val(data.user_image);
$('#button_action').val("수정");
$('#action').val("Edit");
$('#user_id').val(user_id);
}

});

})

});

</script>


#action.php

<?php
include 'crud.php';
$object = new Crud();

if(isset($_POST["action"]))
{
//리스트 조회
if($_POST["action"] == "Load")
{
echo $object -> get_data_in_table("SELECT * FROM users2 ORDER BY id DESC");
}


//삽입
if($_POST["action"] == "Insert")
{
$first_name = mysqli_real_escape_string($object ->connect, $_POST["first_name"]);
$last_name = mysqli_real_escape_string($object ->connect, $_POST["last_name"]);
$image = $object -> upload_file($_FILES["user_image"]);

$query = "
INSERT INTO users2 (first_name, last_name, image) VALUES
('".$first_name."','".$last_name."','".$image."')
";
$object -> execute_query($query);

echo '추가성공';
}

//수정
if($_POST["action"] == "Single")
{
$output = '';
$query = "SELECT * FROM users2 WHERE id = '".$_POST["user_id"]."'";
$result = $object -> execute_query($query);


while($row = mysqli_fetch_array($result))
{
$output["first_name"] = $row["first_name"];
$output["last_name"] = $row["last_name"];
$output["user_image"] = $row["image"];
$output["image"] = '<img src="upload/'.$row["image"].'" class="img-thumbnail" width="50" height="35" />';
}

echo json_encode($output);

}


//수정2

if($_POST["action"]== "Edit")
{
$image = '';

if($_FILES["user_image"]["name"] != '')
{
$image = $object -> upload_file($_FILES["user_image"]);
}else
{
$image = $_POST["hidden_user_image"];
}

$first_name = mysqli_real_escape_string($object ->connect, $_POST["first_name"]);
$last_name = mysqli_real_escape_string($object ->connect, $_POST["last_name"]);

$query = "UPDATE users2 SET first_name ='".$first_name."' ,
last_name = '".$last_name."', image = '".$image."' WHERE id = '".$_POST["user_id"]."' ";
$object -> execute_query($query);
echo "수정 성공";
}



}



?>


#crud.php


<?php

class Crud
{

public $connect;
private $host = "localhost";
private $username = 'root';
private $password = 'eorn1145';
private $database = 'open';

//객체가 생성될때 호출
function __construct()
{
$this -> database_connect();
}

// db 연결 함수
public function database_connect()
{
$this->connect = mysqli_connect($this -> host, $this-> username,
$this->password, $this->database);
}


//쿼리 실행 함수
public function execute_query($query)
{
return mysqli_query($this -> connect, $query);
}

//데이터 조회 함수
public function get_data_in_table($query)
{
$output ='';
$result = $this ->execute_query($query);
$output .= '
<table class="table table-bordered table-striped>"
<tr>
<th width="10%">이미지</th>
<th width="35%">성</th>
<th width="35%">이름</th>
<th width="10%">수정</th>
<th width="10%">삭제</th>
</tr>';

while($row = mysqli_fetch_object($result))
{
$output .= '
<tr>
<td><img src="upload/'.$row->image.'" class="img-thumbnail" width="50" height="35"></td>
<td>'.$row->first_name.'</td>
<td>'.$row->last_name.'</td>
<td><button type="button" name="update" id="'.$row->id.'"
class="btn btn-success btn-xs update">수정</button></td>
<td><button type="button" name="delete" id="'.$row->id.'"
class="btn btn-danger btn-xs delete">삭제</button></td>
</tr>
';
}
$output .='</table>';
return $output;
}

//파일 업로드 함수
function upload_file($file)
{
if(isset($file))
{
$extension = explode('.',$file["name"]);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($file['tmp_name'], $destination);
return $new_name;
}

}

}



?>





반응형

댓글