問題描述
我的問題相當簡單:是否可以將 store_result()
和 bind_result()
與 PHP PDO 一起使用?
My question is fairly straightforward: Is it possible to use store_result()
and bind_result()
with PHP PDO?
這是我遇到的一些示例代碼:
Here is some example code I came across:
$stmt = $mysqli->prepare("SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
$stmt->fetch();
我已經看到這些在 mysqli
的上下文中使用,但沒有在 PHP PDO 中使用.store_result()
和 bind_result()
在 www.php.net 上的 mysqli 中被引用.我很好奇它們是否有效,或者是否有類似的方法.
I have seen these used in the context of mysqli
, but not with PHP PDO. store_result()
and bind_result()
are referenced in mysqli on www.php.net. I'm curious if they are valid, or if there are comparable methods.
顯然這兩種方法之間有一些轉換.我的假設是 store_result
和 bind_result()
類似于 PDO 的 fetch()
命令.
Obviously there is some translation between the two methods. My assumption is that store_result
and bind_result()
are similar to PDO's fetch()
commands.
推薦答案
重點是,在 PDO 中既不使用 store_result() 也不使用 bind_result() 絕對沒有意義.
只需獲取您的數據并在您希望的任何地方使用它.這就是 PDO 的意義所在.
The point is, there is absolutely no point in using neither store_result() nor bind_result() with PDO.
Just get your data and use it anywhere you wish. That's the very point of PDO.
$sql = "SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($email));
$row = $stmt->fetch();
現在您的用戶數據位于 $row
數組中.
Now you have your userdata in $row
array.
將結果行存儲在單獨的變量中現在很少實踐.但是如果你更喜歡這種古老的數據處理方式,你可以添加
Storing resulting row in separate variables is very seldom practice nowadays. But if you prefer such ancient way of dealing with data, you could add
extract($row);
到上面的代碼來獲取你的全局變量.
to the above code to get your global variables.
mysqli-way 的主要問題是它極難以任何抽象級別使用.
The main problem with mysqli-way is that it is extremely hard to use it with whatever level of abstraction.
在現實生活中,我們從不在全局范圍中調用數據庫,而是在這樣的函數中調用
In the real life we never call for database in the global scope, but rather in a function like this
function getUserData() {
// getting data
return $array;
}
出于某種原因,這個簡單但經常使用的代碼在 mysqli 中變得非常困難!在現實生活中,我們不需要單獨的變量,而是需要返回單個數組.但是對于mysqli,我們需要先獲取這些變量,然后將它們放入數組中,然后才返回它們.簡直瘋了!
and for some reason this simple yet mostly used code become extremely difficult with mysqli! In the real life we don't need separate variables but rather single array to be returned. But with mysqli we need to get these variables first, then put them in array and only then return them. Just crazy!
這篇關于是否可以將 store_result() 和 bind_result() 與 PHP PDO 一起使用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!