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

php 좋아요 기능& 알림기능 구현 4 (알림 부분)

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

php 좋아요 기능& 알림기능 구현 4 (알림 부분)  


#화면


#db 모델링


#index.php

<?php
//index.php
include('database_connection.php');
if(!isset($_SESSION["user_id"]))
{
header("location:login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>좋아요 시스템</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>
</head>
<body>
<br />
<div class="container">
<h2 align="center">좋아요 시스템</h2>
<br />
<div align="right">
<a href="logout.php">Logout</a>
</div>
<br />

<!-- 네비게이션 바 -->
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">조아요 - <?php echo $_SESSION['user_name']; ?></a>
</div>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="label label-pill label-danger count"></span> Notification</a>
<ul class="dropdown-menu"></ul>
</li>
</ul>
</div>
</nav>
<br />
<br />

<!-- 담벼락 글 작성란 -->
<form method="post" id="form_wall">
<textarea name="content" id="content" class="form-control" placeholder="무슨생각중?"></textarea>
<br />

<!-- 담벼락 작성버튼 -->
<div align="right">
<input type="submit" name="submit" id="submit" class="btn btn-primary btn-sm" value="Post" />
</div>
</form>
<br />
<br />
<br />
<br />
<h4>최신 글 목록</h4>
<br />

<!-- 최근 글 가져와서 ajax로 붙이기 -->
<div id="website_stuff"></div>
</div>
</body>
</html>

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

load_stuff();

//페이지 로드 될때 글목록 가져오기
function load_stuff()
{
$.ajax({
url:"load_stuff.php",
method:"POST",
success:function(data)
{
$('#website_stuff').html(data);
}
})
}



// 담벼락 전송 버튼 눌렀을 때
$('#form_wall').on('submit', function(event){

// 현재 이벤트의 기본 동작을 중단한다.
//http://programmingsummaries.tistory.com/313

event.preventDefault();
if($.trim($('#content').val()).length == 0)
{
alert("글을 입력해주세요");
return false;
}
else
{

//데이터를 보내기 위해 폼 요소 집합을 문자열로 인코딩 합니다.
// ex single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1


var form_data = $(this).serialize();
//$.ajax의 default Content-Type은 application/x-www-form-urlencoded 이며 이를 통해
//데이터를 전송할 경우 serialize 된 형태로 데이터가 전송됩니다.
//FormData로 전송하기 위해서는 아래와 같이
//processData : false, contentType : false로 세팅하여야 합니다.

//contentType을 false를 해줌으로 써 브라우저로 하여금 FormData를 사용하여 전송 시
//자동으로 content-Type을 multipart/formdata로 세팅하고
//correct boundary를 붙여 데이터를 보낼 수 있게 해줍니다.

//ProcessData의 경우도 마찬가지로 data를 serialize를 하여 Query String으로 변경하기 때문에
//이를 막기 위해 false로 세팅해 줍니다.
//(ProcessData : data를 query string의 형태로 변경시키는 옵션. default 값은 true)

//참고 http://hellowk1.blogspot.kr/2015/07/formdata-file-submit-with-formdata.html
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'done')
{
$('#form_wall')[0].reset();
load_stuff();
}
}
})
}
});
// 좋아요 버튼 눌렀을 때
$(document).on('click', '.like_button', function(){

//참고
//http://www.nextree.co.kr/p10155/
var content_id = $(this).data('content_id');
$(this).attr('disabled', 'disabled');
$.ajax({
url:"like.php",
method:"POST",
data:{content_id:content_id},
success:function(data)
{
if(data == 'done')
{
load_stuff();
}
}
})
});

load_unseen_notification();


//보지 않은 알림
function load_unseen_notification(view = '')
{
$.ajax({
url:"load_notification.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.dropdown-menu').html(data.notification);
if(data.unseen_notification > 0)
{
$('.count').html(data.unseen_notification);
}
}
})
}
$(document).on('click', '.dropdown-toggle', function(){
$('.count').html('');
load_unseen_notification('yes');
});
});
</script>

#load_notification

<?php
//load_notification.php
include('database_connection.php');
if(isset($_POST["view"]))
{
$query = "
SELECT user_content_like.user_id, content.description, user_details.user_name, user_details.user_image FROM user_content_like
INNER JOIN content
ON content.content_id = user_content_like.content_id
INNER JOIN user_details
ON user_details.user_id = user_content_like.user_id
WHERE content.user_id = :user_id
AND user_content_like.status = :status
ORDER BY user_content_like.user_content_like_id DESC
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':user_id' => $_SESSION['user_id'],
':status' => 'not-seen'
)
);
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$user_name = '';
if($row['user_id'] == $_SESSION['user_id'])
{
$user_name = '<img src="images/'.$row["user_image"].'" class="img-thumbnail" width="40" height="40" /> You have';
}
else
{
$user_name = '<img src="images/'.$row["user_image"].'" class="img-thumbnail" width="40" height="40" /> '.$row['user_name'].' has ';
}
$output .= '
<li>
<a href="#">
<strong>'.$user_name.'</strong> like your post "'.substr($row["description"], 0, 25).'"
</a>
</li>
';
}
}
else
{
$output .= '
<li><a href="#" class="text-bold text-italic">No Notification Found</a></li>
';
}
if($_POST["view"] != '')
{
$select_query = "
SELECT * FROM content WHERE user_id = :user_id
";
$statement = $connect->prepare($select_query);
$statement->execute(
array(
':user_id' => $_SESSION['user_id']
)
);
$result = $statement->fetchAll();
foreach($result as $row)
{
$update_query = "
UPDATE user_content_like
SET status = 'seen'
WHERE content_id = :content_id
AND status = :status
";
$statement = $connect->prepare($update_query);
$statement->execute(
array(
':content_id' => $row['content_id'],
':status' => 'not-seen'
)
);
}
}
$statement = $connect->prepare($query);
$statement->execute(
array(
':user_id' => $_SESSION['user_id'],
':status' => 'not-seen'
)
);
$total_row = $statement->rowCount();
$data = array(
'notification' => $output,
'unseen_notification' => $total_row
);
echo json_encode($data);
}


?>

#function.php

<?php

//한 유저가 한 게시물에 좋아요를 눌렀는지 안눌렀는지 체크해주는 함수
// user_id 와 특정 content_id로 조회해서 값이 있으면 좋아요 버튼 누른것
// 없으면 안누른것

function is_user_has_already_like_content($connect, $user_id, $content_id){


$query = "
select * from user_content_like
where content_id = :content_id
and user_id = :user_id;";


$statement = $connect -> prepare($query);

$statement -> execute(
array(':content_id' => $content_id, ':user_id'=> $user_id)
);

$total_rows = $statement -> rowCount();


//값이 있으면
if($total_rows >0){
return true;
}else
{
return false;
}
}
// 게시물이 좋아요 몇번 받았는지 반환
function count_content_like($connect, $content_id){

$query ="
select * from user_content_like
where content_id =:content_id";

$statement = $connect ->prepare($query);
$statement -> execute(
array(':content_id'=> $content_id)
);

$total_rows = $statement -> rowCount();
return $total_rows;
}



?>

#like.php

<?php


include("database_connection.php");


if(isset($_POST["content_id"]))
{

$query = "
insert into user_content_like(content_id, user_id) values(:content_id, :user_id);
";

$statment = $connect ->prepare($query);
$statment -> execute(

array(
':content_id' => $_POST["content_id"],
':user_id' => $_SESSION["user_id"]
)
);

$statment ->fetchAll();

if(isset($statment))
{
echo 'done';
}

}


?>

#insert.php

<?php


include("database_connection.php");



if(isset($_POST["content"]))
{
$query = "
insert into content(user_id, description) values(:user_id, :description)";

$statement = $connect -> prepare($query);
$statement -> execute(
array(
':user_id' => $_SESSION["user_id"],
':description' => $_POST["content"]
)
);

$result = $statement -> fetchAll();
}

if(isset($result)){

echo 'done';

}else{
echo 'done not';
}

?>

#login.php

<?php

include ("database_connection.php");

$msg = '';


// form에서 submit을 눌렀을 때
if(isset($_POST["login"]))
{
//빈칸이 있을때
if(empty($_POST["user_email"]) || empty($_POST["user_password"]))
{
$msg = '<label>빈칸을 채워 주세요</label>';
}else
{
$query = "select * from user_details where user_email = :user_email";

//SQL 구문 템플릿으로 데이터베이스에 생성되고 보내집니다. 특정 값을 명시하지 않은 체 내비둡니다.
//데이터베이스는 SQL 구문 템플릿을 해석, 컴파일하고 질의 최적화를 수행하고, 실행없이 결과를 저장합니다.
$statment = $connect -> prepare($query);


//어플리케이션은 값을 파라미터와 연결하고, 데이터베이스는 구문을 실행합니다. 어플리케이션은 원하는 다른 값에 따라 여러 번 구문을 실행 할 수 있습니다.
$statment -> execute(
array('user_email'=> $_POST["user_email"])
);
$count = $statment ->rowCount();
if($count > 0 )
{ //쿼리 실행
$result = $statment ->fetchAll();
foreach($result as $row)
{
//패스워드가 hash와 맞는지 확인하는 PHP 함수
//입력한 패스워드가 password_hash()로 생성된 해시값에 맞는지 확인
//password_verify($password, $hash
if(password_verify($_POST["user_password"],$row["user_password"]))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
header("location:index.php");
}else
{
$msg='<label>잘못된 비밀번호 입니다.</label>';
}
}

}else
{
$msg='<label>잘못된 이메일 주소 입니다.</label>';
}
}


}

?>




<!DOCTYPE html>
<html>
<head>
<title>php 좋아요 기능과 알림기능</title>
<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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>

<div class="container">
<h2 align="center">좋아요 기능과 알림기능</h2>

<div class="panel panel-default">
<div class="panel-heading">로그인</div>
<div class="panel-body">

<!--login.form -->
<form method = "post">
<span class="text-danger"> <?php echo $msg; ?> </span>

<div class="form-group">
<label>이메일</label>
<input type="text" name="user_email" id="user_email" class="form-control" />
</div>

<div class="form-group">
<label>비밀번호</label>
<input type="password" name="user_password" id="user_password" class="form-control" />
</div>


<div class="form-group">
<input type="submit" name="login" id="login" class="btn btn-info" value="로그인" />
</div>

</form>
<!--login.form 끝 -->

</div>


</div>



</div>



</body>
</html>


#logout.php

<?php


session_start();
session_destroy();
header("location:login.php");

?>


#load_stuff.php

<?php

include("database_connection.php");
include("function.php");



if(isset($_SESSION["user_id"]))
{
$output = '';
$query = "

select content.content_id, content.user_id, content.description,
user_details.user_name, user_details.user_image
from content
inner join user_details
on user_details.user_id = content.user_id
order by content_id desc;
";
$statement = $connect -> prepare($query);
$statement -> execute();
$result = $statement -> fetchAll();
$total_rows = $statement -> rowCount();

if($total_rows >0)
{
foreach($result as $row)
{
$like_button = '';

//행이 없으면 false 리턴, 좋아요 버튼이 안눌렸으면
if(!is_user_has_already_like_content($connect,$_SESSION["user_id"],$row["content_id"]))
{
$like_button = '
<button type="button" name = "like_button"
class="btn btn-info btn-xs like_button" data-content_id ="'.$row["content_id"].'">
좋아염 </button>';
}
// 한 게시물에 좋아요 몇개 확인 함수
$count_like = count_content_like($connect, $row["content_id"]);

$output .= '
<div class="panel panel-default">

<div class="panel-heading">
<h3 class="panel-title">
<img src="images/'.$row["user_image"].'" class="img-thumbnail"
width="40" height="40" /> by '.$row["user_name"].'
<button type="button" name="total-like" id="total-like"
class="btn btn-warning btn-xs">like'.$count_like.'</button>
</h3>

</div>


<div class="panel-body">
'.$row["description"].'
</div>

<div class="panel-footer" align="right">
'.$like_button.'
</div>
</div>';
}
}else
{
$output = '게시물이 없습니다.';
}
echo $output;
}

?>


반응형

댓글