使用准备好的语句从数据库中检索数据

Retrieving data from database using prepared statement

我在从数据库中检索数据时遇到问题。这是我的代码:

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"][=14= 获取数据]

您需要告诉 PHP 在哪个变量中存储结果。有两种方法可以做到这一点:

  1. with bind_result, and then fetch on the statement object,或者
  2. 在结果对象上使用 get_result, and then fetch_assoc(或其他 fetch_* 变体)

1。 bind_result

使用此解决方案,您可以将变量绑定到 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.
    }
}

2。 get_result

您可以使用 get_result 而不是 bind_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
    }
}