php ajax mysql 

특정유저 차단하기 기능 구현


#화면



#login.php


<?php
include('database_connection.php');


$message = '';

if(isset($_POST["login"]))
{
if (empty($_POST["user_email"])|| empty($_POST["user_password"])) {
$message = "<div class='alert alert-danger'>빈칸을 채워주세요</div>";

} else {
//해당 이메일이 있는지 찾기
$query = "
select * from user_details2
where user_email = :user_email
";

$statment = $connect -> prepare($query);
$statment -> execute(
array(
'user_email' => $_POST["user_email"]
)
);

$count = $statment -> rowCount();
if($count > 0) //email 이 있으면 실행
{
$result =$statment -> fetchAll();
foreach($result as $row)
{
//해당 이메일 유저 상태가 active 이면
if($row["user_status"] == 'Active')
{
//입력한 비밀번호와 db에 해슁으로 저장된 비번 매칭
if(password_verify($_POST["user_password"], $row["user_password"]))
{
$_SESSION["type"] = $row["user_type"];
header("location:index.php");
}else
{
$message = '<div class="alert alert-danger">잘못된 비밀번호 입니다</div>';
}


}else
{
$message = '<div class="alert alert-danger">계정이 정지 당했습니다</div>';
}
}
}else
{
$message = "<div class='alert alert-danger'>잘못된 이메일 주소 입니다</div>";
}

}


}


?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>유저 관리</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->


</style>
</head>
<body>
<br>

<div class="container">
<h2>유저 관리하기</h2>
<br>

<div class="panel panel-default">
<div class="panel-heading">로그인</div>
<div class="panel-body">
<form method="post">
<span class="text-danger"><?php echo $message; ?></span>
<div class="form-group">
<div class="form-group">
<label>이메일</label>
<input type="text" name="user_email" id="user_email" class="form-control" />

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

</div>
</div>

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

</div>

</div>


</body>
</html>

#index.php


<?php
include('database_connection.php');


if(!isset($_SESSION["type"])){
header("location:login.php");
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>유저 관리</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->


</style>
</head>
<body>
<br>

<div class="container">
<h2 align="center">유저 관리</h2>
<br>

<div align="right">
<a href="logout.php">로그 아웃</a>
</div>
<br>

<?php
if($_SESSION["type"]=='user'){

echo '<div align="center"><h2>hi... welcome !</h2></div>';
}else
{
?>
<div class="panel panel-default">
<div class="panel-heading">user status</div>
<div class="panel-body">
<span id = "message"> </span>
<div class="table-responsive" id="user_data">

</div>
</div>

</div>


<?php
}
?>
<script>

$(document).ready(function(){
load_user_data();
function load_user_data(){

var action = 'fetch';
$.ajax({
url:"action.php",
method:"POST",
data:{action:action},
success:function (data){
$('#user_data').html(data);
},error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}


})

}

//설정 버튼 눌렀을 때
$(document).on('click', '.action', function(){


//juqery 데이타 속성으로 값을 가져온다!
var user_id = $(this).data('user_id');
var user_status = $(this).data('user_status');
var action = 'change_status';
$('#message').html('');

if (confirm("정말 변경하시겠습니까?"))
{
$.ajax({
url:"action.php",
method:"POST",
data:{user_id:user_id,user_status:user_status, action:action},
success:function(data){

if(data != '')
{
load_user_data();
$('#message').html(data);
}

}
})
}
else
{
return false;
}
});


});

</script>

</div>

</body>
</html>


#logout.php

<?php


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


?>

#database_connect.php

<?php

$connect = new PDO('mysql:host=localhost; dbname=open','root','비번');


session_start();

?>

#action.php

<?php

if(isset($_POST["action"]))
{
include("database_connection.php");

if($_POST["action"]== 'fetch')
{
$output = '';
$query = "select * from user_details2 where user_type = 'user' order by user_name asc";
$statment = $connect -> prepare($query);
$statment ->execute();
$result = $statment -> fetchAll();

$output .= '
<table class="table table-bordered table-striped">
<tr>
<td>이름</td>
<td>이메일</td>
<td>상태</td>
<td>설정</td>
</tr>
';

foreach($result as $row){

$status = '';
//상태가 활성화 이면
if($row["user_status"]=='Active')
{
$status = '<span class="label label-success">활성화</span>';
}else
{
$status = '<span class="label label-danger">비활성화</span>';
}
$output .= '
<tr>
<td>'.$row["user_name"].'</td>
<td>'.$row["user_email"].'</td>
<td>'.$status.'</td>
<td><button type="button" name="action" class="btn btn-info btn-xs action"
data-user_id="'.$row["user_id"].'" data-user_status="'.$row["user_status"].'">설정</td>
</tr> ';
}
$output .= '</table>';
echo $output;
}


//설정 버튼을 눌렀을 때

if($_POST["action"]=='change_status')
{
$status = '';

//상태가 활성이면 비활성으로
if ($_POST["user_status"]=='Active')
{
$status = "Inactive";
} else
{
$status = "Active";
}

//업데이트
$query ='
update user_details2 set user_status = :user_status where user_id = :user_id
';
$statment = $connect ->prepare($query);
$statment->execute(

array(
':user_status' => $status,
'user_id' => $_POST["user_id"]
)
);
$result = $statment ->fetchAll();
//결과가 존재하면 알림창 띄우기
if(isset($result))
{

echo '<div class="alert alert-success">상태가 <strong>'.$status.'</strong>로 변경 되었습니다</div>';

}
}

}

?>


#db 쿼리

CREATE TABLE IF NOT EXISTS `user_details2` (

  `user_id` int(11) NOT NULL,

  `user_email` varchar(200) NOT NULL,

  `user_password` varchar(200) NOT NULL,

  `user_name` varchar(200) NOT NULL,

  `user_type` enum('master','user') NOT NULL,

  `user_image` varchar(150) NOT NULL,

  `user_status` enum('Active','Inactive') NOT NULL

) ;



[초간단] php ajax mysql 페이스북 담벼락 알림기능 구현


#화면

#index.php

<!DOCTYPE html>
<html>
<head>
<title>알림</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
</head>
<body>

<br>
<br>

<div class="container">
<br>
<h2 align = "center">알림 구현</h2>
<br>

<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</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>
알림</a>
<!-- 알림 붙는 곳 -->
<ul class="dropdown-menu"></ul>
</li>

</ul>
</div>
</nav>

<br/>

<form method="post" id="comment_form">
<div class="form-group">
<label>제목</label>
<input type="text" name ="subject" id="subject" class="form-control" />
</div>

<div class="form-group">
<label>본문</label>
<textarea name ="comment" id="comment" class="form-control" rows="5"></textarea>
</div>

<div class="form-group">
<input type="submit" name ="post" id="post" class="btn btn-info" value="post"/>
</div>

</form>


</div>


</body>
</html>

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


//알림 글 가져오기
function load_unseen_notification(view='')
{
$.ajax({

url:"fetch.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);
}
}
})
}

load_unseen_notification();

//글 입력
$('#comment_form').on('submit', function(event){
event.preventDefault();

alert('z');
if($('#subject').val() != '' && $('#comment').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data){
$('#comment_form')[0].reset();
load_unseen_notification();
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}

});


}else{
alert("빈칸을 채워주세요");
}

});

// 알림클릭했을 때 알림 숫자 지워주기
$(document).on('click', '.dropdown-toggle', function(){
$('.count').html('');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);


});


</script>


#fetch.php

<?php

if(isset($_POST["view"]))
{
include("connect.php");


//알림창을 눌렀을 때 0 을 1로 변경 0:안봄 , 1: 봄
if($_POST["view"]!='')
{
$update_query = "update comments set comment_status =1 where comment_status=0";
mysqli_query($connect , $update_query);
}


// 최근글 5개만 가져오기
$query = "select * from comments order by comment_id desc limit 5";
$result = mysqli_query($connect, $query);
$output ='';

if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<li>
<a herf="#">
<strong>'.$row["comment_subject"].'</strong><br>
<small><em>'.$row["comment_text"].'</em></small>
</a>
</li>
';
}


}else
{
$output .= '
<li><a herf="#" class="text-bold text-italic">알림이 없습니다.</a></li>
';

}


//안본글 만 가져와서 숫자 표시해주기
$query_1 = "select * from comments where comment_status = 0";
$result_1 = mysqli_query($connect, $query_1);
$count = mysqli_num_rows($result_1);
$data = array(
'notification' => $output,
'unseen_notification' => $count

);

echo json_encode($data);
}

?>


#insert.php

<?php

include("connect.php");

//insert.php
if(isset($_POST["subject"]))
{

$subject = mysqli_real_escape_string($connect, $_POST["subject"]);
$comment = mysqli_real_escape_string($connect, $_POST["comment"]);


$query = "INSERT INTO comments(comment_subject, comment_text, comment_status) VALUES ('$subject', '$comment' ,0)";
mysqli_query($connect, $query);


}
?>


#connect.php

<?php
//connect.php;
$connect = mysqli_connect("localhost", "root", "비번","db이름");
?>



#테이블 쿼리

 CREATE TABLE IF NOT EXISTS `comments` (

  `comment_id` int(11) NOT NULL,

  `comment_subject` varchar(250) NOT NULL,

  `comment_text` text NOT NULL,

  `comment_status` int(1) NOT NULL

);



php mysql로 facebook 좋아요 구현 단순 핵심소스만!


#db 모델링



#화면

- 좋아요 누르면 카운트

- 좋아요 누른 사람 띄우기

- 한번 더 누르면 삭제, 카운트 리셋


#소스코드


<?php


session_start();

//1 johon
//2 jeck
$_SESSION['user_id'] = (int)2; // 사용자 아이디는 임의로 정해준다. 1 or 2
$connect = mysqli_connect("localhost","root","eorn1145","open");

$query = "
select articles.id, articles.title,
count(article_likes.id) as likes,
group_concat(user1.name separator '|') as liked
from articles
left join article_likes
on article_likes.article = articles.id
left join user1
on article_likes.user = user1.id
group by articles.id
";


$result = mysqli_query($connect, $query);

while($row = mysqli_fetch_array($result))
{
echo '<h3>'.$row["title"].'</h3>';
echo '<a href="index.php?type=article&id='.$row["id"].'">좋아요</a>';
echo '<p>'.$row["likes"].' 명의 사람들이 좋아합니다.</p>';
//echo '<p>'.$row["liked"].'</p>';
if(count($row["liked"]))
{
$liked = explode("|", $row["liked"]);
echo '<ul>';
foreach($liked as $like)
{
echo '<li>'.$like.'</li>';
}
echo '</ul>';
}
}



if(isset($_GET["type"], $_GET["id"]))
{
$type = $_GET["type"];

$id = (int)$_GET["id"]; // 콘텐츠 아이디

if($type == "article")
{
// 1 이상이면 즉 좋아요를 했으면 1
$check_query ="select count(*) as cnt from article_likes where user = {$_SESSION["user_id"]} and article = {$id};";
$result1 =mysqli_query($connect, $check_query);
$row1 = mysqli_fetch_array($result1); //칼럼에 0 아니면 1

//cnt가 1이면 좋아요누른 상태
if($row1["cnt"]==1)
{
// 좋아요 삭제
$query = "
delete from article_likes where article = {$id} and user = {$_SESSION['user_id']};
";

mysqli_query($connect, $query);
header("location:index.php");

}else{

//좋아요 표시
$query = "
insert into article_likes (user, article)
select {$_SESSION['user_id']}, {$id} from articles
where
exists(
select id from articles where id = {$id})
and
not exists(
select id from article_likes where user = {$_SESSION['user_id']} and id = {$id})
limit 1
";

mysqli_query($connect, $query);
header("location:index.php");
}
}
}


// 중간에 mysql 부분 오류 해결
//14:15:05 delete from article_likes where article = 4 and user = 2    Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect. 0.000 sec

//SET SQL_SAFE_UPDATES =0;


?>



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;
}

?>


  1. 2018.05.09 13:01

    비밀댓글입니다

php ajax로 달력만들기 예제 1


php 공부를 시작한지 3주 정도 된것 같다. 시간날 때마다 예제들을 만들어 보고 있다. 추석이 지나면 php도 완전히 감을 잡을 것 같다. 3주간의 공부로 php를 딱 정의하긴 힘들지만 javascript와 java 를 합쳐 놓은 것 같다. javascript기반의 node js 처럼 쉽게 웹서버를 만들수 있고 바로 웹상에 결과물을 띄울 수 있다. 또 배열 선언, if문, for문, 함수형 프로그래밍 같은 개념들이 js와 많이 닮았다. 그리고 자바처럼 객체,캡슐화, 상속, 접근제어자 등의 개념도 있어서 뭔가 견고한 프로그램을 빠르게 많들 수 있지 않을까라는 생각이 든다. 다양한 api도 존재하니 생각했던 것들을 빠르게 구현 가능 할 것 같다. 구체적인건 조금 더 공부를 해봐야 알것 같다. 


#화면 

(디자인은 좀 허접하다... 지난달을 클릭하면 지난달 달력이 출력되고, 다음달 버튼을 누르면 다음달 달력이 출력되게 해놓았다. 데이터는 ajax로 가져온다.)



#index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<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>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<title>calendar</title>


<style>

#main{
border: black 1px solid;
}
#calendar{
border: black 1px solid;
}

table{
width:800px;
height:400px;
text-align:center;
}

th,tr,td{
border: black 1px solid;
}


#b1{
border:1px solid green;
float: left; width: 33%;
}

#a1{
border:1px solid green;
float: left; width: 33%;
}

#m1{
border:1px solid green;
float: left; width: 33%;
}

#box:after{
border:1px solid pink; line-height: 200px; content:""; display:block; clear:both;
}

#before{

width:200px;
height:100px;
}



#after{
width:200px;
height:100px;
}
</style>
</head>



<body>


<div id="result">;
</div>


</body>
</html>

<script>

$(document).ready(function(){

//이번달
load();
function load(){

$.ajax({
url:"now.php",
method:"POST",
success:function(data){
$('#result').html(data);
}

});

}




$(document).on('click', '#before', function(){

var mon = parseInt($('#month').text());
var mon= mon -1;

$.ajax({
url:"before.php",
method:"POST",
data:{mon:mon},
success:function(data){
$('#result').html(data);
}

});

});

$(document).on('click', '#after', function(){

var mon = parseInt($('#month').text());
var mon= mon +1;

$.ajax({
url:"after.php",
method:"POST",
data:{mon:mon},
success:function(data){
$('#result').html(data);
}

});

});





});


</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>


#now.php

(페이지가 로드될때 now.php 를 호출해서 이번달 날짜 데이터를 가져온다.)

<?php
$now_time = time();

$month=date("n",$now_time);
$daily = array('일','월','화','수','목','금','토');
$sec = mktime(0, 0, 0, $month, 1, 2017);
$firstday=date("j",$sec); //1
$lastday=date("t",$sec); //30
$firstyoil=date("w",$sec); //5 //


$output = '';

$output .= '<div id="box">
<div id="b1"><center><input type="button" name="before" id="before" value="지난달"></center></div>
<div id="m1"><h1 align="center" id="month">'.$month.'</h1></div>
<div id="a1"><center><input type="button" name="after" id="after" value="다음달"></center></div>
</div>';

$output .='<table align="center">';
$num = 1;

$output .= '<tr>';

//일 - 토
for($i=0;$i<7;$i++){
$output .= '<td>'.$daily[$i].'</td>';
}

$output .= '</tr>';


//줄
for($i=0; $i<count($daily)-2; $i++)
{

$output.= '<tr id="'.$i.'">';
//칸
for($ii=0; $ii<count($daily);$ii++)
{

if($i==0 && $ii<$firstyoil){
$output .= '<td></td>';
}else{

if($num > $lastday){
$output .= '<td></td>';
}else{
$output .= '<td id="'.$ii.'">'.$num.'</td>';
$num++;
}
}
}

$output .= '</tr>';
}
$output .= '</table>';

echo $output;
?>


#before.php

(지난달 달력 출력)

<?php


$daily = array('일','월','화','수','목','금','토');
$sec = mktime(0, 0, 0, $_POST['mon'], 1, 2017);
$month=date("n",$sec); //달
$firstday=date("j",$sec); //첫째날
$lastday=date("t",$sec); //마지막째날
$firstyoil=date("w",$sec); //첫째날 요일 // 5


$output = '';

$output .='<div id="box"><div id="b1"><center><input type="button" name="before" id="before" value="지난달"></center></div>
<div id="m1"><h1 align="center" id="month">'.$month.'</h1></div>
<div id="a1"><center><input type="button" name="after" id="after" value="다음달"></center></div></div>';
$output .='<table align="center">';
$num = 1;

$output .= '<tr>';
for($i=0;$i<7;$i++){
$output .= '<td>'.$daily[$i].'</td>';
}

$output .= '</tr>';

for($i=0; $i<count($daily)-2; $i++)
{

$output.= '<tr id="'.$i.'">';
for($ii=0; $ii<count($daily);$ii++)
{

if($i==0 && $ii<$firstyoil){
$output .= '<td></td>';
}else{
if($num > $lastday){
$output .= '<td></td>';
}else{
$output .= '<td id="'.$ii.'">'.$num.'</td>';
$num++;
}
}
}

$output .= '</tr>';
}
$output .= '</table>';

echo $output;

?>


#after.php

(다음달 달력 출력)

<?php


$daily = array('일','월','화','수','목','금','토');
$sec = mktime(0, 0, 0, $_POST['mon'], 1, 2017);
$month=date("n",$sec); //달
$firstday=date("j",$sec); //첫째날
$lastday=date("t",$sec); //마지막째날
$firstyoil=date("w",$sec); //첫째날 요일 //


$output = '';

$output .='<div id="box"><div id="b1"><center><input type="button" name="before" id="before" value="지난달"></center></div>
<div id="m1"><h1 align="center" id="month">'.$month.'</h1></div>
<div id="a1"><center><input type="button" name="after" id="after" value="다음달"></center></div></div>';
$output .='<table align="center">';
$num = 1;

$output .= '<tr>';
for($i=0;$i<7;$i++){
$output .= '<td>'.$daily[$i].'</td>';
}

$output .= '</tr>';

for($i=0; $i<count($daily)-2; $i++)
{

$output.= '<tr id="'.$i.'">';
for($ii=0; $ii<count($daily);$ii++)
{

if($i==0 && $ii<$firstyoil){
$output .= '<td></td>';
}else{
if($num > $lastday){
$output .= '<td></td>';
}else{
$output .= '<td id="'.$ii.'">'.$num.'</td>';
$num++;
}

}
}

$output .= '</tr>';
}
$output .= '</table>';

echo $output;

?>


php session을 이용한 간단한 쇼핑 장바구니  구현


#화면



#index.php

<?php

session_start();
$connect = mysqli_connect("localhost","root","비번","db이름");

//name 속성이 add_to_cart 인 form태그에 submit 버튼을 눌렀을때
if(isset($_POST["add_to_cart"]))
{

//쇼핑카트 세션 배열이 존재한다면
if(isset($_SESSION["shopping_cart"]))
{
//참고:https://www.w3schools.com/php/func_array_column.asp
//값이 배열로 이루어진 배열에서 key 값이 item_id인 값을 찾아서 배열로 리턴
$item_array_id = array_column($_SESSION["shopping_cart"],"item_id");

//클릭한 상품의 id가 $item_array_id 배열에 존재 하지 않으면
if(!in_array($_GET["id"], $item_array_id))
{
//shopping_cart 세션 배열에 들어있는 배열의 수
$count = count($_SESSION["shopping_cart"]);
//클릭한 상품의 데이터를 배열에 넣는다.
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);

//shopping_cart 세션 배열에서 그 다음 방부터 차례로 넣는다.
$_SESSION["shopping_cart"][$count] = $item_array;

}else
{
//클릭한 상품의 id가 $item_array_id 배열에 존재한다면
echo '<script>alert("같은 상품이 존재합니다.")</script>';
echo '<script>window.location="index.php"</script>';
}


//쇼핑카트 세션 배열이 존재하지 않는다면(즉, 제일 처음 카트 버튼을 눌렀을 때)
}else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]

);

//key 값이 shopping_cart 인 배열 0번 방에 상품 배열을 넣었다.
$_SESSION["shopping_cart"][0] = $item_array;
//echo var_dump($_SESSION["shopping_cart"]);
//array(1) { [0]=> array(4) { ["item_id"]=> string(1) "1" ["item_name"]=> string(14) "Samsung J2 Pro" ["item_price"]=> string(6) "100.00" ["item_quantity"]=> string(1) "1" } }
//echo var_dump($_SESSION["shopping_cart"][0]);
//array(4) { ["item_id"]=> string(1) "1" ["item_name"]=> string(14) "Samsung J2 Pro" ["item_price"]=> string(6) "100.00" ["item_quantity"]=> string(1) "1" }
}

}


if(isset($_GET["action"]))
{
if($_GET["action"]=="delete")
{
//shopping_cart 세션 배열에 존재하는 배열들을 $values 에 넣는다.
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
//배열의 item_id 값이 클릭한 id 값과 같으면
if($values["item_id"] == $_GET["id"])
{
//세션에서 제거한다.
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("삭제 되었습니다")</script>';
echo '<script>window.location="index.php"</script>';
}
}
}

}





?>

<!DOCTYPE html>
<html>
<head>
<title>php session을 이용한 장바구니</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" style="width:700px;">
<h3 align="center">php session을 이용한 장바구니</h3>
<br>
<?php
$query = "SELECT * FROM tbl_product ORDER BY id ASC";
$result = mysqli_query($connect,$query);

if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<!-- =============반복 되는 상품 리스트 부분=============== -->
<div class="col-md-4">
<!-- action 속성에 주소와 상품 id 번호 담는다 -->
<form method="post" action="index.php?action=add&id=<?php echo $row["id"]; ?> ">
<div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
<img src="<?php echo $row["image"]; ?>" class="img-responsive" /> </br>
<h4 class="text-info"> <?php echo $row["name"]; ?> </h4>
<h4 class="text-danger"> <?php echo $row["price"]; ?> </h4>

<!-- submit 버튼을 누를때 name 속성의 값이 url로 넘어간다. post 방식으로 -->
<input type="text" name="quantity" class="form-control" value="1" />
<input type="hidden" name="hidden_name" value="<?php echo $row["name"] ?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"] ?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="추가"/>
</div>
</form>
</div>
<!-- 반복 되는 상품 리스트 부분 종료-->
<?php
}

}
?>
<div style="clear:both"></div>
<br>

<h3>주문내역</h3>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="40%">상품</th>
<th width="10%">수량</th>
<th width="20%">가격</th>
<th width="15%">총금액</th>
<th width="5%">옵션</th>
</tr>


<?php
//쇼핑카트에 물건이 존재하면!
if(!empty($_SESSION["shopping_cart"]))
{
$total = 0;
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
?>

<tr>
<td><?php echo $values["item_name"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td><?php echo $values["item_price"]; ?></td>
<td><?php echo number_format($values["item_quantity"] * $values["item_price"],2);?></td>
<td><a href="index.php?action=delete&id=<?php echo $values["item_id"]?>"> <span class="text-danger">삭제</span> </a></td>

</tr>

<?php
$total = $total + ($values["item_quantity"] * $values["item_price"]);
} //foreach 끝
?>

<tr>
<td colspan="3" align="right">총금액</td>
<td align="right"><?php echo number_format($total,2);?> </td>
<td></td>
</tr>


<?php
} //if문 끝
?>

</table>
</div>



</div>


</body>
</html>


php login session 예제



#화면


#index.php

<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial</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>
#box
{
width:600px;
background:gray;
color:white;
margin:0 auto;
padding:10px;
text-align:center;
}
</style>
</head>
<body>
<?php
session_start();
if(isset($_SESSION["name"]))
{
echo "<h1 align='center'>Use Ajax with Jquery in PHP to check Session Expired</h1>";
echo "<h1 align='center'>".$_SESSION["name"]."</h1>";
echo "<p align='center'><a href='logout.php'>Logout</a></p>";
}
else
{
header('location:login.php');
}
?>
</body>
</html>
<!--index.php !-->
<script>
$(document).ready(function(){
function check_session()
{
$.ajax({
url:"check_session.php",
method:"POST",
success:function(data)
{
if(data == '1')
{
alert('Your session has been expired!');
window.location.href="login.php";
}else{

alert('session alive');
}
}
})
}
setInterval(function(){ check_session(); }, 3000);
});
</script>


#login.php

<?php
//login.php
$connect = mysqli_connect("localhost", "root", "비번", "db이름");
session_start();
if(isset($_POST["sub"]))
{
$username = mysqli_real_escape_string($connect, $_POST["name"]);
$password = mysqli_real_escape_string($connect, $_POST["pass"]);
$query = "SELECT * FROM session WHERE user = '".$username."' AND password = '".$password."'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
//세션 설정
$_SESSION["name"] = $_POST["name"];
header("location:index.php");
}
else
{
echo '<script>alert("Wrong Data")</script>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial</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>
#box
{
width:600px;
background:gray;
color:white;
margin:0 auto;
padding:10px;
text-align:center;
margin-top:100px;
}
</style>
</head>
<body>
<div id="box">
<h1 align="center">Use Ajax with Jquery in PHP to check Session Expired</h1>
<h2>Login</h2>
<form method="post">
<input type="text" name="name" id="name" placeholder="Enter Username" class="form-control" /><br />
<input type="password" name="pass" id="pass" placeholder="Enter Pass" class="form-control" /><br />
<input type="submit" name="sub" id="sub" class="btn btn-info" value="Submit" />
</form>
<br /><br />
</div>
</body>
</html>


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

function check_session()
{
$.ajax({
url:"check_session.php",
method:"POST",
success:function(data)
{
if(data == '1')
{
alert('Your session has been expired!');
window.location.href="login.php";
}else{

alert('session alive');
}
}
})
}
setInterval(function(){ check_session(); }, 3000);
});
</script>


#logout.php

<?php
//logout.php
session_start();
session_destroy();
header('location:login.php');
?>


#check_session.php

<?php
//check_session.php
session_start();
if(isset($_SESSION["name"]))
{
echo '0'; //session not expired
}
else
{
echo '1'; //session expired
}
?>


php ajax bootstrap datepicker 예제


#화면




#index.php

<?php

$connect = mysqli_connect("localhost" ,"root", "eorn1145","open");
$query = "SELECT * FROM tbl_order ORDER BY order_id desc";
$result = mysqli_query($connect,$query);

?>
<!DOCTYPE html>
<html>
<head>
<title>부트스트랩 달력예제</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>

<!-- 달력 선택 부분 -->
<div class="container" style="width:900px;">
<h2 align="center">부트스트랩 달력예제</h2>
<h3 align="center">주문 날짜</h3>

<div class="col-md-3">
<input type="text" name="from_date" id="from_date" class="form-control" placeholder="from date" />
</div>

<div class="col-md-3">
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="to date" />
</div>


<div class="col-md-5">
<input type="button" name="filter" id="filter" class="btn btn-info" value="필터" />
</div>

<!-- 달력 선택 부분 끝-->

<div style="clear:both"></div>
</br>

<!-- 데이터 출력 부분-->
<div id="order_table">
<table class="table table-bordered">
<tr>
<th width="5%">번호</th>
<th width="40%">이름</th>
<th width="43%">아이템</th>
<th width="10%">value</th>
<th width="12%">주문일</th>

</tr>
<?php
while($row = mysqli_fetch_array($result))
{

?>

<tr>
<td> <?php echo $row["order_id"];?> </td>
<td> <?php echo $row["order_customer_name"];?> </td>
<td> <?php echo $row["order_item"];?> </td>
<td> <?php echo $row["order_value"];?> </td>
<td> <?php echo $row["order_date"];?> </td>
</tr>

<?php
}
?>
</table>
</div>

</div>




</body>
</html>


<script>


//달력 날짜 출력 설정
$.datepicker.setDefaults({
dateFormat:'yy-mm-dd'
});


//부트스트랩 달력 기능
$(function(){

$("#from_date").datepicker();
$("#to_date").datepicker();
});

//필터 버튼 클릭했을 때
$('#filter').click(function(){

//날짜 input text 창에서 값을 가져온다.
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();

//빈칸이 없으면
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date,to_date:to_date},
success:function(data){
$('#order_table').html(data);
}


});

}else
{
alert("날짜를 선택해 주세요");
}

});

</script>



#filter.php

<?php

// 찾을 날짜 데이터를 넣어 준다.
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost","root","암호","db이름");
$output = '';

//쿼리
$query = "

SELECT * FROM tbl_order
WHERE order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'";

//실행
$result = mysqli_query($connect , $query);


//출력 데이터
$output .= '

<table class="table table-bordered">

<tr>
<th width="5%">번호</th>
<th width="40%">이름</th>
<th width="43%">아이템</th>
<th width="10%">value</th>
<th width="12%">주문일</th>
</tr>
';

if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td> '.$row["order_id"].'</td>
<td> '.$row["order_customer_name"].'</td>
<td> '.$row["order_item"].'</td>
<td> '.$row["order_value"].'</td>
<td> '.$row["order_date"].'</td>
</tr>
';
}
}else
{
$output .= '
<tr>
<td colspan="5">데이터가 없습니다.</td>
</tr>
';
}

$output .= '</table>';
echo $output;
}




?>


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


앞의 소스 코드index.php 의 스크립트 부분에서 좋아요 버튼을 클릭했을 때 작동하는 함수와 그것을 처리하는 like.php 를 추가했다


index.php


//좋아요 버튼이 클릭되었을 때
$(document).on('click','.like_button', function(){
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();
}
}

});
});


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)
";

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

$result = $statement->fetchAll();
if(isset($result))
{
echo 'done';
}
}

?>


php 좋아요 기능& 알림기능 구현 2 (좋아요 총개수 불러오기& 글 삽입 기능)



#화면


#경로


index.php

<?php

include("database_connection.php");
if(!isset($_SESSION["user_id"]))
{

header("location:login.php");
}

?>



<!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>
<br />



<div class="container">
<h2 align="center">php 좋아요 기능과 알림기능</h2>
<br />
<div align="right">
<a href="logout.php">로그아웃</a>
</div>
<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){
event.preventDefault();



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

$.ajax({
url:"insert.php",
method:"POST",
data:new FormData(this),
contentType:false,
processData:false,
success:function(data){

if(data == 'done')
{
alert(data);
$('#form_wall')[0].reset();
load_stuff();
}else{
alert(data);
$('#form_wall')[0].reset();
load_stuff();
}
}
});
}

});


});

</script>

login.php

<?php

include("database_connection.php");

$msg = '';

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";
$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)
{
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>
<br />



<div class="container">
<h2 align="center">php 좋아요 기능과 알림기능</h2>
<br />
<div class="panel panel-default">
<div class="panel-heading">로그인</div>
<div class="panel-body">

<!-- 로그인 폼 -->
<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>
</div>
</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 = '';
//행이 없으면, 즉 좋아요 버튼이 안눌렸으면
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"].'
</h3>

<button type="button" name = "total-like" id="total-like"
class="btn btn-warning btn-xs"> '.$count_like.' 좋아요 </button>
</div>
<div class="panel-body">
'.$row["description"].'
</div>

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

echo $output;
}
?>


insert.php

<?php
//insert.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';
}
}

?>


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;
}


?>


database_connection.php

<?php

$connect = new PDO("mysql:host=localhost; dbname=db이름","root","비번");

session_start();
?>


+ Recent posts

티스토리 툴바