I'm writing a 'like' feature for my website and for the life of me, I just can't get this function working!
Assuming this is a simplified version my database structure:
id --- post_id --- user_id
1 --- 1 ----------- 1
2 --- 2 ----------- 1
And this is the code I've written:
public function userHasLikedPost($post_id,$user_id){
$this->post_id_clean = sanitize($post_id);
$this->user_id_clean = sanitize($user_id);
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("SELECT like_type FROM ".$db_table_prefix."post_likes WHERE user_id = ? AND post_id = ?");
$stmt->bind_param("ii", $this->post_id_clean, $this->user_id_clean);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($like_type);
$stmt->fetch();
$result;
if( $stmt->num_rows >0 ){
$result = array("liked" => 1, "like_type" => $like_type);
}else{
$result = array("liked" => 0);
}
return print_r($stmt);
$stmt->close();
}
When I call userHasLikedPost(1,1) my code will return the correct number of rows
mysqli_stmt Object ( [affected_rows] => 1 [insert_id] => 0 [num_rows] => 1 [param_count] => 2 [field_count] => 1 [errno] => 0 [error] => [error_list] => Array ( ) [sqlstate] => 00000 [id] => 5 ) 1
However, if I call userHasLikedPost(2,1) I will get the incorrect number of rows.
mysqli_stmt Object ( [affected_rows] => 0 [insert_id] => 0 [num_rows] => 0 [param_count] => 2 [field_count] => 1 [errno] => 0 [error] => [error_list] => Array ( ) [sqlstate] => 00000 [id] => 5 ) 1
Why is this happening? Am I using mysqli correctly? The data exists in the database, and if I run the query manually in PHPMyAdmin I will get the correct output. I've spent like 2 hours trying to get this one function working... Thanks in advance for any replies :)
I've fixed my problem. My bindings were in the incorrect order :/ How embarrassing haha!
Solution:
Replace this line of code:
$stmt->bind_param("ii", $this->post_id_clean, $this->user_id_clean);
With:
$stmt->bind_param("ii", $this->user_id_clean, $this->post_id_clean);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.