我正在为我的网站写一个“喜欢”的功能,对于我的生活,我只是无法使这个功能正常工作!
假设这是我的数据库结构的简化版本:
id --- post_id --- user_id
1 --- 1 ----------- 1
2 --- 2 ----------- 1
这是我写的代码:
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();
}
当我调用userHasLikedPost(1,1)时,我的代码将返回正确行数
mysqli_stmt对象([affected_rows] => 1 [insert_id] => 0 [num_rows] => 1 [param_count] => 2 [field_count] => 1 [errno] => 0 [错误] => [error_list] => Array()[sqlstate] => 00000 [id] => 5)1
但是,如果我调用userHasLikedPost(2,1),我将得到不正确的行数。
mysqli_stmt对象([affected_rows] => 0 [insert_id] => 0 [num_rows] => 0 [param_count] => 2 [field_count] => 1 [errno] => 0 [错误] => [error_list] => Array()[sqlstate] => 00000 [id] => 5)1
为什么会这样?我正确使用mysqli吗?数据存在于数据库中,如果我在PHPMyAdmin中手动运行查询,我将得到正确的输出。我花了2个小时试图让这个功能正常工作......提前感谢任何回复:)
答案 0 :(得分:2)
我已经解决了我的问题。我的绑定顺序不正确:/多么令人尴尬哈哈!
解决方案:
替换这行代码:
$stmt->bind_param("ii", $this->post_id_clean, $this->user_id_clean);
使用:
$stmt->bind_param("ii", $this->user_id_clean, $this->post_id_clean);