php 中的 get_result() 和 store_result() 有什么区别? [英] What is the difference between get_result() and store_result() in php?

查看:22
本文介绍了php 中的 get_result() 和 store_result() 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.我正在检查登录/注册系统中是否存在用户:

This is my code. I am checking if a user exists or not in a login/registration system:

public function userExist($email){
    $stmt = $this->conn->prepare("select email from users where email= ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows>0){

    }
    else{

    }
}

我可以使用 get_result 代替 store_result() 吗?

Can I use get_result instead of store_result() ?

推荐答案

这取决于您计划如何读取结果集.但是在您给出的实际示例中,您对读取任何返回的数据不感兴趣.您唯一感兴趣的是是否有记录.

It depends on how you plan to read the result set. But in the actual example you have given, you are not interested in reading any returned data. The only thing that interests you is whether there is a record or not.

在那种情况下,您的代码没问题,但它与 get_result 一起工作得同样好.

In that case your code is fine, but it would work equally well with get_result.

差异变得更加明显,例如,当您想要获取具有给定电子邮件的用户的 userid 时:

The difference becomes more apparent, when you want to get for example the userid of the user with the given email:

SELECT id FROM users WHERE email = ?

如果你打算用 $stmt->fetch 读出 id,那么你会坚持store_result,并且会使用 bind_result 来定义你想在哪个变量中获得这个 id,就像这样:

If you plan to read out that id with $stmt->fetch, then you would stick to store_result, and would use bind_result to define in which variable you want to get this id, like this:

$stmt->store_result();    
$stmt->bind_result($userid);  // number of arguments must match columns in SELECT
if($stmt->num_rows > 0) {
    while ($stmt->fetch()) {
        echo $userid;  
    }
}

如果您希望获得一个结果对象,您可以在该对象上调用 fetch_assoc() 或任何 fetch_* 变体方法,那么您需要使用 get_result,例如这个:

If you prefer to get a result object on which you can call fetch_assoc() or any of the fetch_* variant methods, then you need to use get_result, like this:

$result = $stmt->get_result();   // You get a result object now
if($result->num_rows > 0) {     // Note: change to $result->...!
    while ($data = $result->fetch_assoc()) {
        echo $data['id'];
    }
}

请注意,您从 get_result 获取结果对象,而 store_result 则不是这种情况.您现在应该从结果对象中获取 num_rows.

Note that you get a result object from get_result, which is not the case with store_result. You should get num_rows from that result object now.

两种方式都可以,这真的是个人喜好问题.

Both ways work, and it is really a matter of personal preference.

这篇关于php 中的 get_result() 和 store_result() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆