2012-07-17 41 views
3

我的函數看起來像這樣。PHP取數據兩次

private function generateTree($courseID) { 
     $q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?"; 
     $stmt = $this->db->prepare($q); 
     $stmt->bind_param("i", $courseID); 
     $stmt->execute(); 
     $stmt->store_result(); 
     if ($stmt->num_rows > 0) { 
      $stmt->bind_result($id, $lName, $cName); 
      echo "<li> <a href='#'>$cName</a> <ul>"; 
      while ($stmt->fetch()) <====HERE!!! 
       echo "<li> <a href='?course=$courseID&lesson=$id'> $lName </a></li>"; 
      echo "</ul> </li>"; 
     } 
    } 

問題是我開始在一段時間內獲取數據,但是我也需要它。我可以提取兩次數據嗎?還有其他建議嗎?

回答

3

您可以使用fetchAll()來獲取所有數據,並根據需要多次迭代。

$result = $stmt->fetchAll(); // PDO 
$result = $stmt->fetch_all(); // MySQLi 

foreach($result as $row) { print $row['lesson_name']; } 
foreach($result as $row) { print $row['lesson_name']; } 
foreach($result as $row) { print $row['lesson_name']; } 
etc... 

更新:我不完全確定你在做什麼,因爲你似乎有幾個想法混合到你的代碼中。也許你想要這樣的東西?

$q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?"; 
$stmt = $this->db->prepare($q); 
$stmt->bind_param("i", $courseID); 
$stmt->execute(); 

if ($stmt->num_rows > 0) 
{ 
    $results = $stmt->fetch_all(); 

    foreach($results as $row) 
    { 
     print_r($row); 
    } 
} 
+0

這不是PDO,而是事先聲明。另外,我如何循環使用fetchal呢? – heron 2012-07-17 16:33:25

+2

@epic_syntax這裏是mysqli版本:http://php.net/manual/en/mysqli-result.fetch-all.php – Neal 2012-07-17 16:34:42

+0

我正在使用PREPARED STATEMENTS – heron 2012-07-17 16:35:59

2

我覺得你可以讓你的數據庫查詢類,它返回數據庫結果的排列方式。您可以多次使用數據。

可以使數據庫的ResultSet這樣的數組:

while($row = mysql_fetch_assoc($result)) 
{ 
    $results[] = $row; 
} 
3

它已經四年了,但萬一有人偶然發現了這個問題,像我一樣:

while ($stmt->fetch()) { 
    // do your thing 
} 

$stmt->data_seek(0); 

while ($stmt->fetch()) { 
    // do something other 
} 

你可以read documentation here