首页 > 解决方案 > 将普通的 OOP SQLi 语句转换为准备好的语句

问题描述

我有以下正常的用户类语句,我正在尝试将其转换为准备好的语句。

public function didReceiveRequest($user_from) {
    $user_to = $this->user['username'];
    $check_request_query = mysqli_query($this->con, "SELECT * FROM friend_requests WHERE user_to='$user_to' AND user_from='$user_from'");
    if (mysqli_num_rows($check_request_query) > 0) {
        return true;
    }
    else {
        return false;
    }
}

我是准备好的语句的新手,并且在整个 User 类中都做得很好,但仍然有一些问题。作为新手,我也不遵循逻辑,所以请放轻松。这是我到目前为止所拥有的:

public function didReceiveRequest($user_from){
   $user_to = $this->user['username'];
   $check_request = $this->con->stmt_init();
   $check_request->prepare('SELECT * FROM friend_requests WHERE user_to=? AND user_from=?');

   $check_request->bind_param('ss', $user_to, $user_from);
   $check_request->execute();

   $result = check_request->get_result();
   $data = $result->fetch_assoc();

   $check_request->free_result();
   $check_request->close();

   if($data > 0){
      return true;
   }else{
      return false;}
}

所以有几件事:1)我知道可能有更好,更有效的方法来做到这一点。2)我所返回的结果是否与之前的结果(使用正常语句)相同。我不想混淆来自我的依赖页面的调用。

标签: phpmysqliprepared-statement

解决方案


我在作为答案提供的内容中看到的不同之处是$result = $stmt->get_result(); 再次成为准备好的语句的新手,我不是 100% 认为这是上面代码引发错误的原因,但这段代码有效。

 public function didReceiveRequest($user_from) {
    $user_to = $this->user['username'];
    $stmt = $this->con->stmt_init();
    $stmt->prepare('SELECT * FROM friend_requests WHERE user_to=? AND user_from=?');

    $stmt->bind_param('ss', $user_to, $user_from);
    $stmt->execute();

    $result = $stmt->get_result();
    $qty = $result->num_rows;

    $stmt->free_result();
    $stmt->close();

    if($qty > 0) {
        return true;
    }else{
        return false;
    }

}

推荐阅读