簡體   English   中英

PHP如何在while循環之外回顯fetch的結果

[英]PHP How to echo the result of a fetch outside a while-loop

我是面向對象PHP的新手。 目前我正在制作一個登錄腳本,我一直在抓取並回顯結果。 這是我的腳本:

$stmt = $db->mysqli->prepare("select User from `users` where User = ? AND Password = ?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->store_result();
$num = $stmt->num_rows;
$stmt->bind_result($username);

if ( $num !== 1 ) {
    echo 'no result';
} else {
    echo 'Your username: '. $username ;
}

$stmt->close();

正如您所看到的,我沒有在上面的腳本中獲取結果。 我嘗試在$num !== 1之前的while循環中使用$stmt->fetch()

但是,獲取的結果被“存儲”為一個數組(我認為),即使在while循環中你不使用數組(只是$username )。 我想要的:回顯選擇查詢OUTSIDE while循環的結果。 就像有可能以老式的方式(假設只有1個結果,因此沒有必要的while循環):

$result = mysqli_query( $conn, $query );
$record = mysqli_fetch_array( $result );
echo $record['username'];

你需要考慮對象變量:

echo $stmt->User;

或者您可以保存變量以供日后使用:

$user = $stmt->User;

循環結束后, $user將保留該值。

您可以使用$stmt->get_result()來執行此操作,例如

$stmt->execute();
$result = $stmt->get_result();

$record = $result->fetch_assoc();
echo $record['username'];

編輯

另一種方法是在bind_result之后調用fetch

$stmt->bind_result($username);
$stmt->fetch()

echo $username;

舊時尚方式:

print_r($record);

從php手冊: print_r

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM