前提
JavaScriptのfetchでいいね機能を作成している。
実現したいこと
phpのforeachで出力された分を要素ごとに「いいね」できる様にしたい
問題(困っている内容)
いいねボタンを押すとforeachで出力された物の全てにいいねがついてしまう
該当のソースコード
php
1//index.php 2//省略 3echo '<form id="like_form">'; 4 echo '<input id="store_id" type="hidden" name="store_id" value="'.$_SESSION['store_id'].'">'; 5 echo '<input id="user_id" type="hidden" name="user_id" value="'.$_SESSION['user']['user_id'].'">'; 6 $sql=$pdo->prepare(' 7 select * 8 from indeed 9 join favorite 10 where favorite.user_id = "'.$_SESSION['user']['user_id'].'" and indeed.store_id = favorite.store_id 11 '); 12 $sql->execute(); 13 if($sql->rowCount() > 0) { 14 echo '<div class="favorite_button_position">'; 15 echo '<button type="button" name="like_button" value="1"><span id="favorite_text">お気に入り済み</span><img src="img/heart_on.png" alt="heart" id="img_heart"></button>'; 16 echo '</div>'; 17 } else { 18 echo '<div class="favorite_button_position">'; 19 echo '<button type="button" name="like_button" value="0"><span id="favorite_text">お気に入りに登録</span><img src="img/heart_off.png" alt="heart" id="img_heart"></button>'; 20 echo '</div>'; 21 } 22 echo '</form>'; 23//省略
JavaScript
1//fetch.js 2const btn = document.getElementById('like_button'); 3let btn_value = document.getElementById('like_button').value; 4const img = document.getElementById('img_heart'); 5const form = document.getElementById('like_form'); 6 7btn.addEventListener('click', ()=> { 8 if(btn_value == "0") { 9 //切り替え 10 console.log('赤にします'); 11 img.src = "img/heart_on.png"; 12 btn_value = "1"; 13 } else if(btn_value == "1") { 14 //切り替え 15 console.log('黒にします'); 16 img.src = "img/heart_off.png"; 17 btn_value = "0"; 18 } 19 20 const formData = new FormData(form); 21 fetch('like.php', { 22 method: 'POST', 23 body: formData, 24 }) 25 .then(response => response.text()) 26 .then(data => { 27 console.log(data); 28 console.log('done'); 29 }); 30}); 31
php
1//like.php 2require('../DB_connect/db_connect.php'); 3 4if(isset($_POST['store_id'])) { 5 $sql=$pdo->prepare('select * from favorite where store_id = "'.$_POST['store_id'].'" and user_id = "'.$_POST['user_id'].'"'); 6 $sql->execute(); 7 if($sql->rowCount() > 0) { 8 $db=$pdo->prepare('delete from favorite where store_id = "'.$_POST['store_id'].'" and user_id = "'.$_POST['user_id'].'"'); 9 $db->execute(); 10 } else { 11 $db=$pdo->prepare('insert into favorite(store_id, user_id) values("'.$_POST['store_id'].'", "'.$_POST['user_id'].'")'); 12 $db->execute(); 13 } 14} 15
試したこと
jsで連番idを割り振り取得しようとしたが上手くいかなかった
原因
jsで取得したidが同じなので全件に影響してしまっている
補足情報(FW/ツールのバージョンなど)
Mac
VsCode
MySQL
補足2
上手く言葉にできなくてもどかしい部分が多々ありますが、何卒知恵を貸していただきたいです。
回答2件