私は自分の投票システムを機能させようとしています。私は3つのデータベーステーブルを持っています:ユーザー、投稿、投票
テーブルusersには、主キーとしてフィールドusernameがあります。テーブルpostの主キーはpost_idです。(より多くのフィールドがありますが、質問/問題には影響しません)
投票テーブルには、次の3つのフィールドがありますusername, post_id, vote
。投票はenum
('positive', 'negative')
です。私が達成しようとしているのは、ユーザーがページに表示されている特定の投稿に投票した場合、次のクエリを実行することですINSERT INTO votes ('username','post_id','vote') VALUES('$user_name','$post_id', 'positive')
。実行されます。
ユーザー123123
がまだ投稿に投票していない場合に機能します。このユーザーが投稿1に投票すると、このクエリは正常に機能します。しかし、このユーザーが別の投稿に投票したい場合(彼の投票はカウントされます-コードの機能しない部分をコピーしただけで、残りは正常に機能しています)、挿入クエリは実行されません。ユーザーabcd
が特定の投稿に投票したい場合、これは再び正常に機能しますが、1回だけです。データベースに何らかの問題があるように思われるので、同じusername
または。を持つエントリは1つだけpost_id
です。1人のユーザーが複数の投稿に投票できるようにするにはどうすればよいですか?このためのより良い戦略はありますか?
if($runloggedin->num_rows == 1)
{
// If there was no vote for the current posting, then execute this query
$query = "SELECT * FROM posts WHERE post_id='".$post_id."' AND user_name='".$user_name."'"; //get username and the post id
$result = $mysqli->query($query);
$query1 = "SELECT * FROM votes WHERE post_id='".$post_id."' AND username='".$user_name."'"; //check if there is a vote for this post already
$result1 = $mysqli->query($query1);
if ($result->num_rows == 1 && $result1->num_rows == 0)
{
$vote = "INSERT INTO votes ('username','post_id','vote') VALUES('$user_name','$post_id', 'positive')"; // this isn't working. everything else seems to be working (still test it more)
$savevote = $mysqli->query($vote);
$addvote = "UPDATE posts SET posvotes=posvotes+1 WHERE post_id='".$post_id."'";
$runvote = $mysqli->query($addvote);
echo "Thank you for your vote";
}
}