我在从数据库中检索数据时遇到问题。这是我的代码:
function login($email, $password) {
$stmt = $this->conn->prepare("SELECT id FROM lms_admin_users WHERE email=?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 1) {
while ($stmt->fetch()) {
// echo data from table like $data["name"]; <----
}
}
else {
echo "Failed";
}
}
我想知道的是等同于while($data=mysqli_fetch_assoc($result))
来替换现有代码(以OOP方式)while ($stmt->fetch())
并使用$data["name"]
答案 0 :(得分:1)
您需要告诉PHP在哪个变量中存储结果。有两种方法可以做到这一点:
bind_result
,然后fetch
在语句对象上,或get_result
,然后fetch_assoc
(或其他fetch_*
变体)在结果对象上使用此解决方案,您可以将变量绑定到SELECT
列表,而使用fetch
循环时,PHP会将新数据放入这些变量中:
$stmt = $this->conn->prepare("SELECT id FROM lms_admin_users WHERE email=?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $name); // <- Add; #args = #cols in SELECT
if($stmt->num_rows == 1) {
while ($stmt->fetch()) {
echo $id, $name; // <-- then you can do this.
}
}
您可以使用bind_result
而不是get_result
,这将提供一个结果对象,您可以从关联数组中获取每一行:
//...
// $stmt->store_result(); // <- Remove: does not work together with next statement
$result = $stmt->get_result(); // <--- add this instead
if($result->num_rows == 1) { // <--- change to $result->...!
while ($data = $result->fetch_assoc()) {
echo $data['id'], $data['name']; // <--- available in $data
}
}