2014-03-27 18 views
0

我正在製作一個網頁,它將列出表格中的所有用戶帳號。從w3schools嘗試該方法時,它不起作用。我如何能夠用PHP準備的語句來做到這一點?到目前爲止,我有這個代碼,但它只會顯示第一個MySQLi結果,與數據庫中用戶的數量一樣多。MySQLi準備好的語句 - 顯示錶格

<?php 
while($totalusers > 0) { 
    if($stmt = $con -> prepare("SELECT id, username, confirmed FROM users")) { 
     $stmt -> execute(); 
     $stmt -> bind_result($id, $username, $confirmed); 
     $stmt -> fetch(); 
     $stmt -> close(); 
    } 
    $totalusers = $totalusers-1; 
    echo "<tr><td>" . $id . "</td><td>" . $username . "</td><td>" . $confirmed . "</td></tr>"; 
} 
?> 
+0

*「我將如何使用PHP準備的語句來做到這一點?」* ---這是關於[** prepared statements **]的相當不錯的教程(http://www.phpmysqlitutorials.com/2011/04/16/mysqli-whats-the-difference-between-standard-queries-and-prepared-statements /)<= –

回答

0

您準備好了語句並執行$ totaluser次。 你只需要準備並執行一次。 試試這個:

if($stmt = $con -> prepare("SELECT id, username, confirmed FROM users")) { 
     $stmt -> execute(); 
     $stmt -> bind_result($id, $username, $confirmed); 
     while($stmt->fetch()) { 
      echo "<tr><td>" . $id . "</td><td>" . $username . "</td><td>" . $confirmed . "</td></tr>"; 
     } 
     $stmt -> close(); 
} 

我沒有測試的代碼,所以它可能需要一些調整。 如果這是您第一次使用PHP,php.net是學習PHP的好地方。

+0

它大部分看起來不錯。 bind_result需要在execute()之後執行。如果我已經使用bind_result,那麼while($ result-> fetch_assoc()){}工作嗎?如果我沒有bind_result,我可能會使用$ myrow ['username']替換$ username嗎? – Starfire1337

+0

你可以。我更喜歡使用fetch_assoc,然後在while循環中使用$ myrow ['id'],$ myrow ['username']和$ myrow ['confirmed'],而不是bind_result。 – kruger