2013-01-16 35 views
0

我想檢查查詢是否帶來結果。現在,我爲我的查詢創建一個行計數。如果rowcount> 0,則我再次創建一個新的查詢,獲取查詢的所有結果。當我在a-z範圍內進行字母順序查詢循環(即WHERE name LIKE "a%")時,將導致52個查詢完成任務,這有​​點超出了imo。你如何面對這樣的任務?結果我想呈現一個帶有字母順序鏈接的菜單。PDO檢查結果是否存在並呈現字母菜單

A 
---- 
Apple Link 
Annanas Link 

B 
---- 
Banana Link 

etc. 

也許有另一種方式做,在一個查詢和exlopde以某種方式的結果字母,因爲我需要渲染的每個字母新引入menupoint。我希望你有一些有用的指針來調整我的表現

回答

2

你不能一次選擇所有的東西,並按列排序嗎?

SELECT * FROM your_table ORDER BY column_name ASC 

然後你就可以通過,如果有行和比較的第一個字母來決定你是什麼字母循環:

$stmt->execute(); 
if ($stmt->rowCount()) { 
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     $value = $row['column_name']; 
     $first_letter = $value[0]; 
    }  
} 

一旦你的第一個字母,你可以做任何你想要的值

要在這個答案擴展,你可以使用這樣的呼應了同一個標題中的值:

// initialize this variable 
$current_letter = ''; 

// if you get results 
if ($stmt->rowCount()) { 
    // loop through each row 
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     // when you loop, get the value 
     $value = $row['column_name']; 
     // if the value does not have the current letter you are on: 
     if ($current_letter != $value[0]) { 
      // echo a header for the new letter 
      echo "<h2>" . $value[0] . "</h2>"; 
      // set the new letter to the current letter 
      $current_letter = $value[0]; 
      // echo the actual value 
      echo $value . "<br />"; 
     } else { 
      // the value falls under our current letter, echo it 
      echo $value . "<br />"; 
     } 
    } 
} 
+0

非常好的答案,很好的評論,從中學習!我很感激 – Johnny000

相關問題