#問題点
$.postで特定の投稿のIdに対する、likes_countというカラムの値を返したいのですが上手くいきません。
具体的には、postsテーブルのlikes_countの値は、いいねボタンをクリックするたびに増えるのですが、ブラウザ上に表示される値はそれとは一致せず、1と表示されます。
原因がわからないので、教えていただきたいです。
#ソースコード
index.php
<section class="images"> <ul class="img_row"> <?php $sql = "SELECT * FROM posts ORDER BY id desc;"; $stmt = $pdo->prepare($sql); $stmt -> execute(); while ($row = $stmt -> fetch(\PDO::FETCH_ASSOC)): ?> <li> <?php echo ("<a href='/images/$row[file_name]'>"); echo ("<img src='/thumbs/$row[file_name]' class='img' id ='$row[id]'></a>"); ?> <div class="heart icon"></div> <div class="likes_count" id="likes_count"></div> </li> <?php endwhile; ?> </ul> </section> <script> $(function() { 'use strict'; $('.icon').on('click', function() { $(this).css('color', 'red'); $.post('Countup.php', { id: $('img').attr('id'), mode: 'update' }, function(data){ $('#likes_count').text(data); }); }); }); </script>
Countup.php
<?php require_once(__DIR__ . '/Login/config/config.php'); require_once(__DIR__ . '/Like.php'); $likeApp = new \MyApp\Like(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { try { $res = $likeApp->post(); return $res; // header('Content-Type: application/json'); // echo json_encode($res); // exit; } catch (Exception $e) { header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); echo $e->getMessage(); exit; } } ?>
Like.php
<?php namespace MyApp; class Like { private $pdo; public function __construct() { try { $dsn = "mysql:dbhost=localhost;dbname=dotinstall_sns_php"; $username = "dbuser"; $password = "mu4uJsif*"; $this->pdo = new \PDO($dsn, $username, $password); $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } catch (\PDOException $e) { echo $e->getMessage(); exit; } } public function post() { if (!isset($_POST['mode'])) { throw new \Exception('mode not set!'); } if (!isset($_POST['id'])) { throw new \Exception('[update] id not set!'); } $id = $_POST['id']; $this->pdo->beginTransaction(); $sql = "UPDATE posts set likes_count = likes_count+1 where id = :id;"; $stmt = $this->pdo->prepare($sql); $stmt->bindValue(":id", $id, \PDO::PARAM_INT); $stmt->execute(); $sql = "SELECT likes_count from posts where id = :id;"; $stmt = $this->pdo->prepare($sql); $stmt->bindValue(":id", $id, \PDO::PARAM_INT); $likes_count = $stmt->execute(); $this->pdo->commit(); // return [ // 'likes_count' => $likes_count // ]; echo $likes_count; } } ?>
回答1件
あなたの回答
tips
プレビュー