2014-01-14 41 views
0

我試圖使用以下代碼獲取所有行。在這裏你可以看到echo $row['UserName'];echo $row['Address'];我可以從數據庫中獲取所有用戶名和地址。但是當我在while循環之外使用這個編碼($uname = $row['UserName'];echo $uname;$uaddress = $row['Address'];echo $uaddress;)時,它總是獲取最後一行值。我的問題是如何獲取while循環之外的所有行值?pdo所有行都不會在外部循環訪問

<?php 
     include('config.php'); 

     try 
     { 
      $stmt = $conn->prepare('SELECT * FROM ebusers'); 
      $conn->errorInfo(); 
      $stmt->execute(); 
      while($row = $stmt->fetch()) 
      { 
       echo "<a target=_blank href='edit.php?id=". $row['UserID'] ."'>Edit</a>"; 
       echo "<br>"; 
       echo "<a target=_blank href='delete.php?id=". $row['UserID'] ."'>Delete</a>"; 
       echo $row['UserName']; 
       $uname = $row['UserName']; 
       echo "<br>"; 
       echo $row['Address']; 
       $uaddress = $row['Address']; 
       echo "<br>"; 
      } 
     } 
     catch(PDOException $e) 
     { 
      'Error : '.$e->getMesssage(); 
     } 

     echo $uname; 
     echo $uaddress; 
    ?> 

回答

0

他們只是傳遞到一個數組

while($row = $stmt->fetch()) 
      { 
       echo "<a target=_blank href='edit.php?id=". $row['UserID'] ."'>Edit</a>"; 
       echo "<br>"; 
       echo "<a target=_blank href='delete.php?id=". $row['UserID'] ."'>Delete</a>"; 
       echo $row['UserName']; 
       $uname[] = $row['UserName']; // An array of usernames... 
       echo "<br>"; 
       echo $row['Address']; 
       $uaddress[] = $row['Address']; // An another array of addresses 
       echo "<br>"; 
      } 

//Below two statements prints all usernames and addresses 
print_r($uname); // or you can access like echo $uname[2] to view the second username 
print_r($uaddress); // similarly you can do like that as you did for $uname.. 

//or if you want to loop through individually , you can make use of a foreach construct 
foreach($uname as $usernames) 
{ 
    echo $usernames."<br>"; 
} 
+0

其工作。但是我得到這樣的輸出'Array([0] => Administrator [1] => Rahul Dravid)''。如何正確獲取詳細信息,如Administartor,Rahul Dravid。當我使用echo $ uname;我得到這下面的輸出'陣列' – Karuppiah

+0

這就是爲什麼我給你一個'foreach'構造。評論'print_r'語句並嘗試一下。 –

+0

好的。現在我得到了所有的行。但是這也是在循環內部使用的。我想在循環之外做這些事情。例如'foreach($ uname as $ usernames){$ fname = $ usernames; } echo $ fname;' – Karuppiah

0

在while循環中,$row變量得到每次執行時間覆蓋。

您可以嘗試FetchAll爲您準備陣列。

相關問題