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 배열관련 함수2


#두개 이상의 배열에서 키를 비교해서 서로 다른 키 값을 리턴한다.

<?php



//array_diff_key();
// 이 함수는 두개 이상의 배열에서 키를 비교해서 서로 다른 키 값을 리턴한다.

//array_diff() - value 값만 비교한다.

//array_diff_assoc() 키와 값을 둘다 비교한다.

//문법: array_diff_key(배열1,배열2);

$color = array("red","green","blue","black");
$color2 = array("red","green","blue");

$difference_array = array_diff_key($color,$color2);

echo '<pre>';
print_r($difference_array);
echo '</pre>';


echo '<hr>';


$color3 = array(
"a1" => "red",
"b2" => "green",
"c3" =>"blue",
"d4" => "black"
);


$color4 = array(
"d1" => "red",
"b2" => "blue",
"c3" =>"green"
);


$difference_array = array_diff_key($color3,$color4);

echo '<pre>';
print_r($difference_array);
echo '</pre>';


?>


#모든 키를 값과 교체를 한다.

<?php



//array_flip();

// 모든 키를 값과 교체를 한다.

//array_flip(array);

$fruits = array("oranges","apples","banana");
$flipped = array_flip($fruits);

echo '<pre>';
print_r($flipped);
echo '</pre>';

echo '<hr>';



$color = array(
"101" => "red",
"102" => "green",
"103" => "blue"

);

$flipped2 = array_flip($color);
echo '<pre>';
print_r($flipped2);
echo '</pre>';

?>

#배열의 값을 비교하여 같은 값만 리턴한다.


<?php



//array_intersect();
//배열의 값을 비교하여 같은 값만 리턴한다.


$color1 = array(
"a1" => "red",
"b2" => "green",
"c3" =>"blue",
"d4" => "black"
);


$color2 = array(
"d1" => "red",
"b2" => "blue",
"c3" =>"green"
);


$color3 = array(
"d1" => "yellow",
"b2" => "blue",
"c3" =>"silver"
);


$array_intersect = array_intersect($color1,$color2,$color3);

echo '<pre>';
print_r($array_intersect);
echo '</pre>';

?>


#배열의 키를 비교하여 같은 값만 리턴한다.




//array_intersect_key();
//배열의 키를 비교하여 같은 값만 리턴한다.


$color1 = array(
"a1" => "red",
"b2" => "green",
"c3" =>"blue",
"d4" => "black"
);


$color2 = array(
"d1" => "red",
"b2" => "blue",
"c3" =>"green"
);



$array_intersect_key = array_intersect_key($color1,$color2);

echo '<pre>';
print_r($array_intersect_key);
echo '</pre>';


echo '<hr>';


$countries = array(

'af' => 'africa',
'ko' => 'korea',
'us' => 'usa',
'ja' => 'japan',
);


$selection = array('af','ja');


$flipped = array_flip($selection);
$filtered = array_intersect_key($countries, $flipped);

echo '<pre>';
print_r($filtered);
echo '</pre>';


?>


'PHP 박살내기 > php 배열' 카테고리의 다른 글

php 배열관련 함수2  (0) 2017.09.26
php 배열관련 함수1  (0) 2017.09.22

php date 날짜 관련 함수



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>성공</title>


<style>

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

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

</style>
</head>
<body>
<h1 align="center">달력 만들기 - 부제 코딩 습관</h1>

<h4>1. defaults 로 설정되어있는 현재 시간. 객체다</h4>

<?php $date = new DateTime(); print_r($date); ?> <br>

<?php echo $date->date; ?> <br>

<?php echo $date->getTimestamp(); ?> <br>



<h4>2. int time ( void ) 함수 1970년 1월 1일 0시 0분 0초부터 지금까지 지나온 초를 정수형태로 리턴</h4>

<?php

$now_titmestamp = time();

echo $now_titmestamp;

?>

<h4>3. date()는 time()으로 구해진 타임스탬프를 읽기 좋게 포멧팅</h4>

<?php

$now_titmestamp = time();

echo date("Y-m-d h:i:s",$now_titmestamp);

?>


<h4>4. mktime()은 날짜정보를 입력해서 타임스탬프를 구할 수 있는 함수</h4>

<?php
$sec = mktime(0, 0, 0, 9, 1, 2017);
echo '1970년 1월 1일 0시 0분 0초부터 9월 1일 까지의 초:'.$sec;
echo '<br>';

$sec = mktime(0, 0, 0, 9, 1, 2017);
$yoil=date("D",$sec);
echo '9월 첫째 요일:'.$yoil;
echo '<br>';

$sec = mktime(0, 0, 0, 9, 1, 2017);
$firstyouil=date("j",$sec);
echo '9월 첫째 날짜:'.$firstyouil;
echo '<br>';

$sec = mktime(0, 0, 0, 9, 1, 2017);
$lastday=date("t",$sec);
echo '9월 마지막 날짜:'.$lastday;
echo '<br>';


$sec = mktime(0, 0, 0, 9, $lastday, 2017);
$lastyouil=date("D",$sec);
echo '9월 마지막 날짜 요일:'.$lastyouil;
echo '<br>';


$now_time = time();
$month=date("n",$now_time);
echo '이번달은'.$month.'월입니다';
echo '<br>';

$now_time = time();
$week=date("W",$now_time);
echo '이번주는'.$week.'번째 주입니다';
echo '<br>';

//0 (for Sunday) through 6 (for Saturday)
$now_time = time();
$todayyoil=date("w",$now_time);
echo '오늘은'.$todayyoil.'요일 입니다';
echo '<br>';


$daily = array('일','월','화','수','목','금','토');
$date5 = date('w'); //0 ~ 6 숫자 반환
echo $daily[$date5];

?><br>






<h4>5. 날짜 설정하기</h4>

<?php $date = new DateTime('tomorrow'); print_r($date); ?> <br>

<?php $date = new DateTime('March 24,2013'); print_r($date); ?> <br>



<h4>6. 날짜 비교하기1</h4>

<?php
$one = new DateTime('tomorrow');
$two = new DateTime('March 24,2013');

if($one > $two)
{
echo "one 이 two 보다 큽니다 <br>";
}

$diff = $one -> diff($two); print_r($diff);
?><br>



<h4>7. 날짜 비교하기2</h4>

<?php
$date1=date_create("2013-01-01");
$date2=date_create("2013-02-10");
$diff=date_diff($date1,$date2);

// %a outputs the total number of days
echo $diff->format("총 날짜: %a.");
echo "<br>";

// %R outputs + beacause $date2 is after $date1 (a positive interval)
echo $diff->format("총날짜: %R%a.");
echo "<br>";

// %d outputs the number of days that is not already covered by the month
echo $diff->format("Month: %m, days: %d.");
?>

<br>


<h4>8. 요일 구하기</h4>

<?php
$daily = array('일','월','화','수','목','금','토');
$date = date('w'); //0 ~ 6 숫자 반환
echo $daily[$date];
?>


<h4>9. 타임존</h4>

<?php $date3 = new DateTime('now', new DateTimeZone('Asia/Seoul')); print_r($date3); ?><br>
<?php echo $date3->format("Y-m-d H:i"); ?><br>


<?php $date3 = new DateTime('yesterday'); echo '어제 날짜:'.$date3->format("Y-m-d");?><br>
<?php echo '오늘 날짜:'.$date3->format("Y-m-d"); ?><br>
<?php $date3 = new DateTime('tomorrow'); echo '내일 날짜:'.$date3->format("Y-m-d");?>




<h4>10. dateperiod 사용하기</h4>
<?php $period = new dateperiod($two , new DateInterval('P3D'), $one);

foreach($period as $datetime){

printf('<li>%s</li>',$datetime ->format('Y-m-d'));
}

?>
<?php

$yoyill = array("일","월","화","수","목","금","토");

?>


<div id="main">
<div id="top" align="center">
<span> 2017-9-22</span>
</div>


<div id="content" align="center">
<table id="calendar">
<tr>
<?php
$daily = array('일','월','화','수','목','금','토');
$today_yoil = date('w'); //0 ~ 6 숫자 반환
for($i=0;$i<7;$i++){
?>

<th> <?php echo $daily[$i]; ?></th>
<?php
}
?>

</tr>
<!-- 요일 부분 끝 -->


<?php //줄
for($i1=0; $i1<5;$i1++){
?>
<tr>

<?php //칸

for($i2=0;$i2<7;$i2++){

//if(){
?>
<td><?php echo $i2; ?></td>

<?php
//}
}
?>

</tr>
<?php
}
?>
</table>

</div>

</div>


<?php //9월 1일 부터 30일
$daily = array('일','월','화','수','목','금','토');
$sec = mktime(0, 0, 0, 9, 1, 2017);
$firstday=date("j",$sec); //1
$lastday=date("t",$sec); //30
$firstyoil=date("w",$sec); //5 //금
?>

<div id="content" align="center">
<table id="calendar">
<tr>
<?php
$daily_ = array('일','월','화','수','목','금','토');
$today_yoil = date('w'); //0 ~ 6 숫자 반환
for($i=0;$i<7;$i++){
?>

<th> <?php echo $daily_[$i]; ?></th>
<?php
}
?>

</tr>
</table>

<table>
<?php
// 요일 부분 끝

echo '<tr>';
for($firstday;$firstday<$lastday+1;$firstday++){



echo $firstday.' : ' ; // 1
$sec_yoil = mktime(0, 0, 0, 9, $firstday, 2017);
$yoil=date("w",$sec_yoil);
echo $daily[$yoil].'<br>'; //5
};


?>
</table>


</div>

</body>
</html>


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 배열관련 함수1


1.배열의 종류

<?php
//php 배열 종류는 3가지있다.


//1 indexed arrays
//array(value1, value2, value3,....);

$color = array("red","green","blue");

for($i = 0; $i< count($color);$i++){

echo $color[$i];
echo '<br>';
}

echo '<hr>';

foreach($color as $row){

echo $row;
echo '<br>';
}

echo '<hr>';

//2 associative array
// array(
// key1 => value1,
// key2=> value2
// )

$color2 = array(
'1' => "red",
'2' => "green",
'3' => "blue"
);

foreach($color2 as $keys => $values){
echo $keys . '=>' .$values . '</br>';
}


echo '<hr>';

//3 mulidimensional array

$color3 = array(

'red' => array("reditem1","reditem2","reditem3"),
'green' => array("greenitem1","greenitem2","greenitem3"),
'yellow' => array("yellowitem1","yellowitem2","yellowitem3")
);

//2중 포문으로 풀어 낸다
foreach($color3 as $keys => $values){
echo '색깔--' .$keys. '<br>';

foreach($values as $sub_row)
{
echo '색깔 아이템' . $sub_row. '<br>';
}
}


?>


2.key 값을 대문자 또는 소문자로 출력하기

array_change_key_case(array, case(option));

<?php
//배열의 key 값을 소문자 or 대문자로 바꾸는 함수
//array_change_key_case();

//array_change_key_case(array, case(option));

//배열 선언
$emp = array(

'jon' => 25,
'kim' => 26,
'song' => 27
);

//소문자
echo '<pre>';
print_r(array_change_key_case($emp));
echo '</pre>';

echo '<hr>';


//대문자
echo '<pre>';
print_r(array_change_key_case($emp,CASE_UPPER));
echo '</pre>';
?>


3.배열을 나누어서 두개의 배열로 만드는 함수

array_chunk(array,size,preserve_key)

<?php

// 배열을 나눠서 또다른 배열을 만드는 함수
//array_chunk();
//array_chunk(array,size,preserve_key)


$color = array("red","green","blue","yellow","gold","black");

$chunk_array = array_chunk($color,3);

echo '<pre>';
print_r($chunk_array);
echo '</pre>';


echo '<hr>';

//value값들 출력
foreach($chunk_array as $row)
{
foreach($row as $sub_row){
echo $sub_row.'<br>';
}
}


echo '<hr>';


//키값과 value 값 다 나오게하기

$emp = array(

'jon' => 25,
'kim' => 26,
'song' => 27,
'jin' => 28,
'nam' => 29
);

$chunk_array2 = array_chunk($emp,2,true);
echo '<pre>';
print_r($chunk_array2);
echo '</pre>';


foreach($chunk_array2 as $row){

foreach($row as $sub_key => $sub_rows){
echo $sub_key .'=>' . $sub_rows. '</br>';
}
}

?>


4.배열안의 value가 배열인 값들 중에서 해당 key 값의 value만 출력하는 함수

array_column(array,column_key,index_key);

<?php

//array_column()
//array_column(array,column_key,index_key);


$emp_data = array(

array(
'id' => 1001,
'name' => 'kim',
'gender' => 'male',
'city' => 'deagoo'
),

array(
'id' => 1002,
'name' => 'kang',
'gender' => 'male',
'city' => 'busan'
),


array(
'id' => 1003,
'name' => 'hong',
'gender' => 'male',
'city' => 'seoul'
),

array(
'id' => 1004,
'name' => 'jin',
'gender' => 'male',
'city' => 'deagoo'
)
);

//배열이 value인 값들 중에서 key 값이 name 사람들만 출력
$name = array_column($emp_data,"name");

echo '<pre>';
print_r($name);
echo '</pre>';


echo '<hr>';

//배열이 value인 값들 중에서 key 값이 name 사람들만 출력하는데 해당 id를 key 값으로 같이 출력하라
$name2 = array_column($emp_data,"name","id");

echo '<pre>';
print_r($name2);
echo '</pre>';



?>


5.두 배열을 하나로 합치기 , 첫 배열의 value 값은 합쳐진 후 key가 되고 뒤의 배열은 value 값이 된다.

array_combine(키, 값);

<?php

//array_combine()
// array_combine(키, 값);

$color = array("red","black","white");
$hash_code =array("#ff000","#99999","#adfda");

$array = array_combine($color,$hash_code);

echo '<pre>';
print_r($array);
echo '</pre>';




// 배열과 배열을 합치기

echo '<hr>';

$color2 = array(
'c1' => "red",
'c2' => "black",
'c3' => "white"
);


$hash_code2 = array(
'h1' => "aaaaaa",
'h2' => "bbbbbb",
'h3' => "cccccc"
);

$array2 = array_combine($color2,$hash_code2);
echo '<pre>';
print_r($array2);
echo '</pre>';


?>


6. value의 동일한 개수 구하기

array_count_values(array);

<?php



//array_count_values();
// array_count_values(array);

$color = array("red","red","red","green","green","green","green","green","yellow","gold");


$count_array = array_count_values($color);

echo '<pre>';
print_r($count_array);
echo '</pre>';
?>


7.두 배열을 비교해서 서로 다른 값이 있는 것을 배열에 넣어 리턴 하는 함수

array_diff(array1,array2);

<?php



//array_diff();
//array_diff();


$color = array("red","green","yellow","gold","hi","wow");

$color2 = array("red","green","yellow","gold");

$difference_array = array_diff($color,$color2);


echo '<pre>';
print_r($difference_array);
echo '</pre>';


echo '<hr>';



//이런 종류의 배열은 안됨 그래서

$color1 = array(

array('color' => "red"),
array('color' => "green"),
array('color' => "blue"),
array('color' => "yellow")

);

$color2 = array(

array('color' => "red"),
array('color' => "green"),
array('color' => "blue")

);

//빈배열만들고
$value1= array();
$value2= array();

//풀어주기
foreach($color1 as $row1)
{
$value1[] = $row1["color"];
}

foreach($color2 as $row2)
{
$value2[] = $row2["color"];
}

$difference_array = array_diff($value1,$value2);


echo '<pre>';
print_r($difference_array);
echo '</pre>';

?>


'PHP 박살내기 > php 배열' 카테고리의 다른 글

php 배열관련 함수2  (0) 2017.09.26
php 배열관련 함수1  (0) 2017.09.22

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


+ Recent posts

티스토리 툴바