問題描述
這是我的代碼.我正在檢查登錄/注冊系統(tǒng)中是否存在用戶:
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() ?
推薦答案
這取決于您計劃如何讀取結(jié)果集.但是在您給出的實際示例中,您對讀取任何返回的數(shù)據(jù)不感興趣.您唯一感興趣的是是否有記錄.
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.
差異變得更加明顯,例如,當(dāng)您想要獲取具有給定電子郵件的用戶的 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;
}
}
如果您希望獲得一個結(jié)果對象,您可以在該對象上調(diào)用 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
獲取結(jié)果對象,而 store_result
則不是這種情況.您現(xiàn)在應(yīng)該從結(jié)果對象中獲取 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.
這篇關(guān)于php 中的 get_result() 和 store_result() 有什么區(qū)別?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!