php - 将普通的 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)我所返回的结果是否与之前的结果(使用正常语句)相同。我不想混淆来自我的依赖页面的调用。
解决方案
我在作为答案提供的内容中看到的不同之处是$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;
}
}
推荐阅读
- c++ - 可变参数模板参数的问题
- javascript - 大表的Angular 6性能问题
- sql - 如何摆脱由于 PLSQL linesize 大于每行中的数据而导致的空格?
- c# - 在不同视图中使用下拉列表中的文本值
- node.js - nodejs s3存储桶上传脚本可重用
- ruby-on-rails - Rails 记录神秘冻结,默默丢弃更新
- c# - 更新关系为映射表的子集合的 EF 友好方式
- php - 如何在 Laravel 中实现自定义频道通知
- mariadb - 在联机服务器上工作时如何使用外键
- chapel - 如何将 Chapel 字符串传递给需要(非常量)char* 的 C 函数?