2016-11-20 49 views
0

我期待在構建一個簡單的應用程序,將顯示數據的表。 csv中的數據是用戶,用戶組,季度,年度,估計和實際成本。形式用於搜索CSV輸出中結果爲使用PHP

到目前爲止,我已經管理這只是輸出整個csv。

<form id="search" method="get" action="search.php"> 
       <input type="text" class="input" name="q" size="21" maxlength="120"><input type="submit" value="search" class="button"> 
     </form> 

    <?php 
    $row = 1; 
    if (($handle = fopen("test.csv", "r")) !== FALSE) { 
     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 
      $num = count($data); 
      echo "<p> $num fields in line $row: <br /></p>\n"; 
      $row++; 
      for ($c=0; $c < $num; $c++) { 
       echo $data[$c] . "<br />\n"; 
      } 
     } 
     fclose($handle); 
    } 
    ?>  

我希望它的工作,這樣,如果我有一個搜索頁面的頂部,用戶提交按鈕來提供搜索參數(S)我會怎麼做,這樣說用戶或用戶組被搜查到它會以表格格式輸出它?

我想可能會分開最佳實踐的HTML表單。

+0

是。來自用戶的輸入需要一個表單。 – RST

+0

我不得不推出這種回到問題的前一次迭代。這不是一個論壇 - 請不要不斷更新你的問題,因爲你正在處理你正在做的事情。一個新問題是一個新問題。 – bcmcfc

+0

你的問題,幫助我,但因爲我有一個新的問題,我會提出一個新的問題。 –

回答

0

爲用戶輸入添加一個表單,下面的添加應該讓你開始。

您可能會希望使其比直接匹配比匹配更強大。例如,一年的範圍,或大於X估計的成本。

堆疊檢查和使用continue允許用戶篩選多個選項。

<?php 

$searchYear = isset($_GET['year']) ? (int) trim($_GET['year']) : null; 
$searchUser = isset($_GET['user']) ? trim($_GET['user']) : null; 


// define some constants for the columns in the CSV 
// in case someone decides to change the format of it 
define('CSV_INDEX_USER', 0); // user is at column 1 (index 0) in the CSV 
define('CSV_INDEX_YEAR', 3); // year is at column 4 (index 3) in the CSV 

$row = 1; 
$output = []; 

if (($handle = fopen("test.csv", "r")) !== FALSE) { 
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 
     $num = count($data); 
     echo "<p> $num fields in line $row: <br /></p>\n"; 
     $row++; 

     // if the user tried to search on year and it doesn't match, continue skips to the next row 
     // casting ensures we compare integers with integers 
     if (!empty($searchYear) && (int) $data[CSV_INDEX_YEAR] !== $searchYear) { 
      continue; 
     } 

     // if the user tried to search on user and it doesn't match, skip 
     if (!empty($searchUser) && $data[CSV_INDEX_USER] !== $searchUser) { 
      continue; 
     } 

     $output[] = $data; 
    } 
    fclose($handle); 
} 
?> 

// HTML

<?php if (!empty($output)): ?> 
    <table> 
     <tr> 
      <th>Your</th> 
      <th>Table</th> 
      <th>Headings</th> 
      <th>Here</th> 
     <tr> 
     <?php foreach ($output as $row): ?> 
     <tr> 
      <td><?=$row[0]?></td> 
      <td><?=$row[1]?></td> 
      <td><?=$row[2]?></td> 
      <td><?=$row[3]?></td> 
     </tr> 
     <?php endforeach; ?> 
    </table> 
<?php endif; ?> 
+0

謝謝,我會試一試。我只是在查看顯示用戶組用戶的估算值和實際成本。 –

+0

@RobertB不用擔心。如果它幫助,請考慮接受了答案:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – bcmcfc

+0

不知道你的意思。如果用戶將所有記錄都留空,則上述操作將返回所有記錄。 – bcmcfc