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

查看:636
本文介绍了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天全站免登陆