mysql - Get posts of a thread and 0 or 1 if the user asking liked the post -
one more time turn asking mysql, not best skill. in fact, seems not complex. simplified scenario, have 2 tables, 1 posts, likes posts:
table post_forum structure
id thread post likes user_id created
table likes_to_post structure
id post_id user_id created
this query obtain posts $start $next thread $thread_id:
$query = "select post_forum.id, post_forum.user_id, post_forum.post, post_forum.likes, post_forum.created post_forum post_forum.thread ='{$thread_id}' order post_forum.id desc limit $start,$next";
what want por every post, 0
or 1
value field saying if user $user_id
has liked every post, being $user_id
id of user asks post, in 1 query if possible. lot in advance, appreciated.
$query = "select a.id, a.user_id, a.post, a.likes, a.created, if(b.user_id not null,1,0) post_forum left join likes_to_post b on b.user_id=$user_id , a.id = b.post_id a.thread ='{$thread_id}' order a.id desc limit $start,$next";
this query: returns 1
if liked , 0
if no:
however should use mysqli or pdo prevent security attacks
edit
mysqli example(i'm not sure thread_id, suppose it's number):
$query = "select a.id, a.user_id, a.post, a.likes, a.created, if(b.user_id not null,1,0) post_forum left join likes_to_post b on b.user_id=? , a.id=b.post_id a.thread ='{?}' order a.id desc limit ?,?"; //connect datatabase $mysqli = new mysqli($hostname, $username, $password, $databasename); $stmt = $mysqli->stmt_init(); $stmt->prepare($query); $stmt->bind_param('iiii', $user_id,$thread_id,$start,$next) $stmt->execute() $stmt->store_result(); $result = $stmt->bind_result($id, $user_id, $post, $likes, $created,$liked); if($stmt->num_rows>0){ while (mysqli_stmt_fetch($stmt)) { [do something] } }
Comments
Post a Comment