main.php
<?php
include_once ("../lib/db_connect.php");
$member=member(); //회원정보
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="author" content="">
<title>My To Do List</title>
<meta name="title" content="My To Do List" />
<meta name="description" content="My To Do List />
<meta name="keywords" content="HTML,CSS,javascript" />
<meta property="og:type" content="My To Do List">
<meta property="og:title" content="My To Do List">
<meta property="og:description" content="My To Do List">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div id="myDIV" class="header">
<div id="top-menu">
<?php
if(isset($member['user_id'])){
echo '<small><a href="#" >'.$member['name'] ."님 환영합니다. </a> </small>";
echo '<small><a href="process/logout_process.php">로그 아웃 </a> </small>';
}else{
echo '<small><a href="index.php"> 로그인</a> </small>';
}
?>
</div>
<h2 style="margin: 5px">My To Do List</h2>
<input type="text" id="myInput" placeholder="Title..."> <span onclick="newElement()" class="addBtn">Add</span>
</div>
<ul id="myUL"></ul>
<script src="js/app.js"></script>
</body>
</html>
app.js
todoList();
//업데이트 - 목록 클릭시 checked 클래스 추가
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
var todo_id=ev.target.id.split("-")[1];
var state = ev.target.classList.contains("checked");
console.log("state : "+state);
//체크드 업데이트
fetch('process/updateTodo.php',{
method:'POST',
cache:'no-cache',
headers:{
'Content-Type': 'application/json; charset=utf-8'
},
body:JSON.stringify({
todo_id:todo_id,
state:state?"1":"0"
})
})
.then((res)=>res.json())
.then((data)=>{
if(data.result=="success"){
console.log("체크 업데이트 성공");
}else{
console.log("체크 업데이트 실패");
console.log(data);
}
});
}
}, false);
//추가
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("내용을 입력하세요!");
} else {
// document.getElementById("myUL").appendChild(li);
document.getElementById("myUL").prepend(li);
}
document.getElementById("myInput").value = "";
fetch(
'process/writeTodo.php',{
method:'POST',
cache:'no-cache',
headers:{
'Content-Type':'application/json; charset=utf-8'
},
body:JSON.stringify({
title:inputValue
})
})
.then((res) => res.text())
.then((data) => {
const json=JSON.parse(data);
if(json.result=="success"){
//등록 성공시 목록 다시 불러오기
// todoList();
}else{
console.log("등록 실패");
console.log(json);
}
});
}
//삭제 - close 버튼 클릭시
function deleteTodo(id){
if(confirm("정말 삭제 하시겠습니까?")){
fetch(
'process/deleteTodo.php',{
method:'POST',
cache:'no-cache',
headers:{
'Content-Type':'application/json; charset=utf-8'
},
body:JSON.stringify({
todo_id:id
})
}
)
.then((response)=>response.json())
.then((data)=>{
if(data.result=="success"){
//삭제 성공시 목록 다시 불러오기
todoList();
}else{
console.log("삭제 실패");
console.log(data);
}
});
}
}
//목록 - 불러오기
function todoList(){
fetch('process/getTodoList.php', {
method: 'POST',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
})//fetch실행을 JS 다른애한테 준다. 이걸하는동안 다른 걸 실행한다.
.then((res) => res.text()) //첫번째 then에서는 server에서 보내준 response를 object형태로 변환한다.
.then((data) => {
//1. (response)=>response.json() json 형태로 받아온다.
//2. (response)=>response.text() text 형태로 받아온다.
//const json=JSON.parse(data); 필요
const json=JSON.parse(data);
//console.log(json);
console.log("todo 갯수 :" , json.todoList.length);
const todoList=json.todoList;
let html="";
for(var i=0; i<todoList.length; i++){
const checkClass=todoList[i].state==0? "": "class='checked'";
html +=`<li id="todo-${todoList[i].todo_id}" ${checkClass} >${todoList[i].title}<span class="close" onclick="deleteTodo(${todoList[i].todo_id})" >×</span></li>`;
}
document.getElementById("myUL").innerHTML=html;
});
}
lib/db_connect.php
<?php
//에러 출력
error_reporting(E_ALL);
ini_set("display_errors", 1);
if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
session_start();//세션 시작
}
function dbconn(){
$host_name="localhost"; //호스트네임
$db_user_id=""; //DB
$db_name=""; //DB아이디
$db_pw=""; //DB비번
//mysqli_connect([아이피], [아이디], [비밀번호], [DB명], [포트]);
$connect = mysqli_connect($host_name,$db_user_id,$db_pw, $db_name,'3306') or die("연결에 실패 하였습니다....");
return $connect;
}
function pdoConn(){
$host_name="localhost"; //호스트네임
$db_user_id=""; //DB
$db_name=""; //DB아이디
$db_pw=""; //DB비번
//$dbh = new PDO("mysql:host=127.0.0.1;dbname=test_db", 'root', 'root-password');
$dbh = new PDO("mysql:host=localhost;dbname=".$db_name, $db_user_id, $db_pw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function myAlert($msg , $id){
$result=array("result"=>"errorMsg", "msg"=>$msg, "id"=>$id);
echo(json_encode($result));
exit;
}
//암호화
function myEncrypted($key, $param){
// 256 bit 키를 만들기 위해서 비밀번호를 해시해서 첫 32바이트를 사용합니다.
$key = substr(hash('sha256', $key, true), 0, 32);
// Initial Vector(IV)는 128 bit(16 byte)입니다.
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
// 암호화
$encrypted = base64_encode(openssl_encrypt($param, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv));
return $encrypted;
}
//복호화
function myDecrypted($key, $encrypted){
// 256 bit 키를 만들기 위해서 비밀번호를 해시해서 첫 32바이트를 사용합니다.
$key = substr(hash('sha256', $key, true), 0, 32);
// Initial Vector(IV)는 128 bit(16 byte)입니다.
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
$decrypted = openssl_decrypt(base64_decode($encrypted), 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
return $decrypted;
}
//로그인 회원 세션 정보
function member(){
global $connect;
$member="";
if(isset($_SESSION["member"])){
$member =$_SESSION["member"];
}
return $member;
}
?>
getTodoList.php
<?php
header("Content-Type: application/json; charset=UTF-8");
include ('../lib/db_connect.php');
$conn = dbconn();
$sql = "select * from todo_list order by todo_id desc ";
$result = mysqli_query($conn, $sql);
$rows = array();
while ($row = $result->fetch_array()) {
$rows[] = $row;
}
$return_result = array(
"result" => "sucess",
"todoList" => $rows
);
// JSON_UNESCAPED_UNICODE ->한글 깨짐 방지 처리
echo json_encode($return_result, JSON_UNESCAPED_UNICODE);
mysqli_close($conn);
exit();
?>
writeTodo.php
<?php
header("Content-Type: application/json; charset=UTF-8");
include_once ("../lib/db_connect.php");
$connect = dbconn();
// JSON.stirngify() 함수로 전달 받기
$post_data = json_decode(file_get_contents('php://input'));
if ($post_data->title == ''){
$return_result=array("result"=>"error", "msg" =>"제목을 입력해 주세요.");
//JSON_UNESCAPED_UNICODE ->한글 깨짐 방지
echo(json_encode($return_result ,JSON_UNESCAPED_UNICODE));
exit();
}
$result=null;
$return_result=null;
try{
$query = "insert into todo_list( `title`) values(?)";
$stmt = $connect->prepare($query);
$stmt->bind_param("s", $post_data->title);
$result=$stmt->execute();
$stmt->close();
$connect->close();
if (count($result) > 0) {
$return_result=array("result"=>"success", "title" =>$post_data->title);
} else {
$return_result=array("result"=>"error", "objct" =>$post_data);
}
}catch (Exception $e){
$return_result=array("result"=>"error", "exception" =>$e);
}
//JSON_UNESCAPED_UNICODE ->한글 깨짐 방지 처리
echo(json_encode($return_result ,JSON_UNESCAPED_UNICODE));
exit();
?>
updateTodo.php
<?php
header("Content-Type: application/json; charset=UTF-8");
include_once ("../lib/db_connect.php");
$connect = dbconn();
// JSON.stirngify() 함수로 전달 받기
$post_data = json_decode(file_get_contents('php://input'));
if ($post_data->todo_id == ''){
$return_result=array("result"=>"error", "msg" =>"todo_id null");
//JSON_UNESCAPED_UNICODE ->한글 깨짐 방지
echo(json_encode($return_result ,JSON_UNESCAPED_UNICODE));
exit();
}
$result=null;
$return_result=null;
try{
$query = "UPDATE todo_list SET state=? WHERE todo_id = ? ";
$stmt = $connect->prepare($query);
$stmt->bind_param("ss", $post_data->state, $post_data->todo_id);
$result=$stmt->execute();
$stmt->close();
$connect->close();
if (count($result) > 0) {
$return_result=array("result"=>"success", "todo_id" =>$post_data->todo_id);
} else {
$return_result=array("result"=>"error", "todo_id" =>$post_data->todo_id);
}
}catch (Exception $e){
$return_result=array("result"=>"error", "exception" =>$e);
}
//JSON_UNESCAPED_UNICODE ->한글 깨짐 방지 처리
echo(json_encode($return_result ,JSON_UNESCAPED_UNICODE));
exit();
?>
deleteTodo.php
<?php
header("Content-Type: application/json; charset=UTF-8");
include_once ("../lib/db_connect.php");
$connect = dbconn();
// JSON.stirngify() 함수로 전달 받기
$post_data = json_decode(file_get_contents('php://input'));
if ($post_data->todo_id == ''){
$return_result=array("result"=>"error", "msg" =>"todo_id null");
//JSON_UNESCAPED_UNICODE ->한글 깨짐 방지
echo(json_encode($return_result ,JSON_UNESCAPED_UNICODE));
exit();
}
$result=null;
$return_result=null;
try{
$query = "DELETE FROM todo_list WHERE todo_id =?";
$stmt = $connect->prepare($query);
$stmt->bind_param("s", $post_data->todo_id);
$result=$stmt->execute();
$stmt->close();
$connect->close();
if (count($result) > 0) {
$return_result=array("result"=>"success", "todo_id" =>$post_data->todo_id);
} else {
$return_result=array("result"=>"error", "todo_id" =>$post_data->todo_id);
}
}catch (Exception $e){
$return_result=array("result"=>"error", "exception" =>$e);
}
//JSON_UNESCAPED_UNICODE ->한글 깨짐 방지 처리
echo(json_encode($return_result ,JSON_UNESCAPED_UNICODE));
exit();
?>












댓글 ( 4)
댓글 남기기