2012-03-21 39 views
1

我是面向對象PHP的新手。目前,我正在製作一個登錄腳本,並堅持要取回&以迴應結果。這是我的腳本:PHP如何在while循環之外回顯提取結果

$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),獲取的結果仍然以數組形式存儲(我認爲)。 我想要的: echo選擇查詢OUTSIDE while循環的結果。正如有可能在老式的方式(假設只有1條結果,因此沒有必要while循環):

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

回答

2

您需要accses到對象變量:

echo $stmt->User; 

也可以保存變量之後:

$user = $stmt->User; 

循環結束後,您的$user將保留該值。

+0

對'$ stmt-> User'沒有喜悅,說屬性不存在。我用'$ username'代替它,並且工作。非常感謝 :) – Tom 2012-03-21 19:49:10

1

您可以使用$stmt->get_result()要做到這一點,例如

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

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

編輯

另一種方法是調用bind_result後取

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

echo $username; 
+0

我試過了,但我得到的方法不存在錯誤。根據PHP.net,它僅適用於mysqlnd。不知道那是什麼,但顯然我沒有。 – Tom 2012-03-21 19:39:42

+0

你是對的,我已經編輯了答案,包括沒有這種依賴性的另一種方法。 – MrCode 2012-03-21 20:53:56

0

舊時尚的方式:

print_r($record); 

從PHP手冊:print_r