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

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

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

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;


?>



반응형

댓글