[PHP] 좋은 기능 구현

18857 단어 PHP
PHP에 대해서는 학습 내용을 메모로 요약합니다.

좋은 기능


PHP에서 aax처리いいね機能를 실현했기 때문에 여기서 실현 방법을 총괄해 보겠습니다.
좋은 기능은 페이스북과 트위터에서 가장 좋아하는 기능을 가리킨다.

버튼 설치


먼저 실현いいねボタン.
적당한 곳에 버튼을 설치하세요.
#user_disp.php

//ユーザーIDと投稿IDを元にいいね値の重複チェックを行っています
function check_favolite_duplicate($user_id,$post_id){
    $dsn='mysql:dbname=db;host=localhost;charset=utf8';
    $user='root';
    $password='';
    $dbh=new PDO($dsn,$user,$password);
    $sql = "SELECT *
            FROM favorite
            WHERE user_id = :user_id AND post_id = :post_id";
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array(':user_id' => $user_id ,
                         ':post_id' => $post_id));
    $favorite = $stmt->fetch();
    return $favorite;
}

<form class="favorite_count" action="#" method="post">
        <input type="hidden" name="post_id">
        <button type="button" name="favorite" class="favorite_btn">
        <?php if (!check_favolite_duplicate($_SESSION['user_id'],$post_id)): ?>
          いいね
        <?php else: ?>
          いいね解除
        <?php endif; ?>
        </button>
</form>
상술한 바와 같이 클릭いいねボタンcheck_favolite_duplicate 함수가 투고를 좋아하는지 판단
버튼을 いいね 또는 いいね解除 로 전환하는 중입니다.
물론 이렇게 하면 aax 처리를 하지 않기 때문에 자바스크립트를 사용해야 한다.
js 파일을 만들고 다음 내용을 추가합니다.

js 파일 만들기

//URLから引数に入っている値を渡す処理
function get_param(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return false;
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


$(document).on('click','.favorite_btn',function(e){
    e.stopPropagation();
    var $this = $(this),
        page_id = get_param('page_id'),
        post_id = get_param('procode');
    $.ajax({
        type: 'POST',
        url: 'ajax_post_favorite_process.php',
        dataType: 'json',
        data: { page_id: page_id,
                post_id: post_id}
    }).done(function(data){
        location.reload();
    }).fail(function() {
      location.reload();
    });
  });
상기 처리에서 클래스 이름 favorite_btn 단추를 눌렀을 때ajax_post_favorite_process.phppage_idpost_id에 넘겨 처리한다.
get_param은 URL에서 매개변수의 값을 읽어들일 수 있습니다.
이 함수에 따라 page_id(사용자 ID) 및post_id.

aax 처리 추가


그렇다면 ajax_post_favorite_process.php 에서 진행된 처리를 살펴보자.
<script src=" https://code.jquery.com/jquery-3.4.1.min.js "></script>
<script src="../js/user_page.js"></script>
<?php
session_start();
session_regenerate_id(true);
require_once('config.php');

function check_favolite_duplicate($user_id,$post_id){
    $dsn='mysql:dbname=db;host=localhost;charset=utf8';
    $user='root';
    $password='';
    $dbh=new PDO($dsn,$user,$password);
    $sql = "SELECT *
            FROM favorite
            WHERE user_id = :user_id AND post_id = :post_id";
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array(':user_id' => $user_id ,
                         ':post_id' => $post_id));
    $favorite = $stmt->fetch();
    return $favorite;
}

if(isset($_POST)){

  $current_user = get_user($_SESSION['user_id']);
  $page_id = $_POST['page_id'];
  $post_id = $_POST['post_id'];

  $profile_user_id = $_POST['page_id'] ?: $current_user['user_id'];

  //既に登録されているか確認
  if(check_favolite_duplicate($current_user['id'],$post_id)){
    $action = '解除';
    $sql = "DELETE
            FROM favorite
            WHERE :user_id = user_id AND :post_id = post_id";
  }else{
    $action = '登録';
    $sql = "INSERT INTO favorite(user_id,post_id)
            VALUES(:user_id,:post_id)";
  }

  try{
    $dsn='mysql:dbname=shop;host=localhost;charset=utf8';
    $user='root';
    $password='';
    $dbh=new PDO($dsn,$user,$password);
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array(':user_id' => $current_user['code'] , ':post_id' => $post_id));

  } catch (\Exception $e) {
    error_log('エラー発生:' . $e->getMessage());
    set_flash('error',ERR_MSG1);
    echo json_encode("error");
  }
}

check_favolite_duplicate 함수를 통해 현재 사용자 ID와 투고 ID를 취득하여 데이터베이스의 조합이 중복되었는지 확인
중복된 상태에서 좋아요를 해제했습니다.
중복되지 않으면favorite 테이블에user_id와post_id를 추가합니다.
이렇게 하면 다음과 같은 화면에서 보여준 괜찮은 단추를 실현하고 표에도 열을 추가했다.


↓ 좋아요 클릭


위와 같은 화면이 되어 데이터베이스를 업데이트하면 성공합니다.
여기서 사용자 ID는 7이고 투고 ID는 13입니다.

참조 URL

좋은 웹페이지 즐겨찾기