테스트 사이트 - 개발 중인 베타 버전입니다

별빵주기

· 6개월 전 · 624 · 4

데이터베이스

[code]

 

CREATE TABLE `g5_rating_log` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `bo_table` VARCHAR(191) NOT NULL,
  `wr_id` INT NOT NULL,
  `mb_id` VARCHAR(191) NOT NULL,
  `rating` INT NOT NULL,
  `regdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unq_rating` (`bo_table`, `wr_id`, `mb_id`)
);
 

[/code]

 

view.skin.php 페이지 원하는위치에 

[code]

<?php
// 평균, 총 평가 수, 본인 평가 여부
$sql = "SELECT AVG(rating) AS avg_rating, COUNT(*) AS total FROM g5_rating_log WHERE bo_table = '$bo_table' AND wr_id = '{$view['wr_id']}'";
$row = sql_fetch($sql);
$avg = round($row['avg_rating'], 1);
$total = $row['total'];

$my_rating = 0;
if ($is_member) {
    $mb_id = $member['mb_id'];
    $res2 = sql_fetch("SELECT rating FROM g5_rating_log WHERE bo_table = '$bo_table' AND wr_id = '{$view['wr_id']}' AND mb_id = '$mb_id'");
    $my_rating = isset($res2['rating']) ? (int)$res2['rating'] : 0;
}
?>

<!-- 별점 UI -->
<select class="star_rate" id="star_rating">
    <option value="">선택</option>
    <?php for ($i = 1; $i <= 5; $i++) { ?>
        <option value="<?= $i ?>"><?= $i ?></option>
    <?php } ?>
</select>

<div style="margin-top: 5px;">
    평균 별점: <span id="star_point"><?= $avg ?></span>점 /
    참여자: <span id="star_cnt"><?= $total ?></span>명
</div>

<!-- Bar Rating 플러그인 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-bar-rating@1.2.2/dist/themes/fontawesome-stars-o.css">
<script src="https://cdn.jsdelivr.net/npm/jquery-bar-rating@1.2.2/dist/jquery.barrating.min.js"></script>

<!-- SendAjax 클래스 -->
<script>
function SendAjax() {
    this.url = '';
    this.send = function(params, callback) {
        $.ajax({
            url: this.url,
            type: 'POST',
            data: params.sendData,
            dataType: 'json',
            success: callback,
            error: function() {
                alert("서버 통신 실패");
            }
        });
    }
}
</script>

<!-- Rate 클래스 -->
<script>
var Rate = function(){};

Rate.prototype = {
    insertRate : function(menu_id, content_type, content_base, content_id, point){
        var _this = this;
        var ajax = new SendAjax();
        ajax.url = '/bbs/insertrate.php';
        var input = {
            loading: false,
            sendData: {
                menu_id: menu_id,
                content_type: content_type,
                content_base: content_base,
                content_id: content_id,
                rt_point: point
            }
        };
        ajax.send(input, function(data){
            if (data.response == 'success') {
                _this.showRate(menu_id, content_type, content_base, content_id, data.data['point'], data.data['cnt'], true, true);
            } else {
                alert(data.msg || "에러 발생");
            }
        });
    },
    showRate : function(menu_id, content_type, content_base, id, point, cnt, is_member, already_rated) {
        var _this = this;
        $('.star_rate').barrating('destroy');
        $('.star_rate').barrating({
            theme: 'fontawesome-stars-o',
            initialRating: point,
            readonly: !is_member || already_rated,
            onSelect: function(value, text, event) {
                if (!is_member) {
                    alert("로그인 후 별점을 등록할 수 있습니다.");
                    return false;
                }
                if (already_rated) {
                    alert("이미 평가하셨습니다.");
                    return false;
                }

                if (typeof(event) !== 'undefined') {
                    _this.insertRate(menu_id, content_type, content_base, id, value);
                }
            }
        });

        $("#star_point").text(point);
        $("#star_cnt").text(cnt);

        if (!is_member) {
            $('<div class="star_notice">로그인 후 별점을 등록할 수 있습니다.</div>').insertAfter('.star_rate');
        } else if (already_rated) {
            $('<div class="star_notice">이미 평가하셨습니다.</div>').insertAfter('.star_rate');
        }
    }
};

$(function() {
    var rate = new Rate();
    rate.showRate(
        '<?= $bo_table ?>',
        'board',
        '<?= $bo_table ?>',
        '<?= $view['wr_id'] ?>',
        '<?= $avg ?>',
        '<?= $total ?>',
        <?= $is_member ? 'true' : 'false' ?>,
        <?= $my_rating > 0 ? 'true' : 'false' ?>
    );
});
</script>

[/code]

bbs 폴더에 아래 파일 생성

insertrate.php

[code]

<?php
include_once('../common.php');

header('Content-Type: application/json');

// 로그인 확인
if (!$is_member) {
    echo json_encode(['response' => 'fail', 'msg' => '로그인 후 별점을 등록할 수 있습니다.']);
    exit;
}

$menu_id = $_POST['menu_id'];
$content_id = (int)$_POST['content_id'];
$point = (int)$_POST['rt_point'];

$bo_table = $menu_id;
$mb_id = $member['mb_id'];

// 이미 평가했는지 확인
$row = sql_fetch("SELECT COUNT(*) AS cnt FROM g5_rating_log WHERE bo_table = '$bo_table' AND wr_id = '$content_id' AND mb_id = '$mb_id'");
if ($row['cnt'] > 0) {
    echo json_encode(['response' => 'fail', 'msg' => '이미 평가하셨습니다.']);
    exit;
}

// 저장
sql_query("INSERT INTO g5_rating_log (bo_table, wr_id, mb_id, rating, regdate) VALUES ('$bo_table', '$content_id', '$mb_id', '$point', NOW())");

// 평균 재계산
$row = sql_fetch("SELECT AVG(rating) AS avg, COUNT(*) AS cnt FROM g5_rating_log WHERE bo_table = '$bo_table' AND wr_id = '$content_id'");
$avg = round($row['avg'], 1);
$total = $row['cnt'];

echo json_encode(['response' => 'success', 'data' => ['point' => $avg, 'cnt' => $total]]);
?>
 

[/code]

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

댓글 4개

6개월 전
감사합니다 ^^
6개월 전

감사합니다 

6개월 전
감사합니다 잘 쓰겠습니다
6개월 전

감사합니다^^

게시글 목록

번호 제목
24149
24140
24133
24125
24119
24109
24105
24101
24093
24089
24077
24074
24071
24070
24067
24056
24050
24046
24043
24040
24037
24036
24035
24034
24021
24017
24005
24002
23990
23980