2016-05-10 54 views
0

下午好,PHP HTML 5表圈

我使用以下軟件:

PHP 5.6版 HTML5 sqlsrv_query

我目前正在寫表了這樣:

<?php 
// Return Results 
$sql = "select warehouse,product from table1"; 

$stmt = sqlsrv_query($conn, $sql); 

$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); 
?> 
<!-- Create table head --> 
<table> 

<th>Warehouse</th><th>Product</th> 

<?php 
// Create table body 
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) 
{ 
echo 
    "<tr> 
    <td>". 
    $row['warehouse']. 
    "</td><td>". 
    $row['product']. 
    "</td> 
    </tr>" 
    ; 
} 
sqlsrv_free_stmt($stmt); 
?> 

我想知道兩件事...

  1. 是否有可能通過循環訪問列名以使用循環語句創建表頭而不是手動輸入每個列名稱?

  2. 是否可以循環遍歷行名而不指定每行的名稱?

我完全是PHP的新手,所以如果我寫了任何反向/不高效的請告訴我!

感謝,

+0

你可以做到這一點與sqlsrv_get_field功能http://php.net/manual/en/function.sqlsrv-get-field.php使用或檢查文檔,並獲取在相關聯的方式排列。 http://php.net/manual/en/function.sqlsrv-fetch-array.php#refsect1-function.sqlsrv-fetch-array-parameters – manuerumx

+0

你所做的是有點正確的。一切都是可能的,你只需要瞭解事情的工作方式。你正在循環$ row,這是一個數組。你已經知道你可以用數組做一個循環,所以只需在你的'$ row'元素上使用'foreach'並試着讓這些東西起作用。您將能夠獲取數組的鍵和值,以便您可以自動構建整個表。 – Unex

回答

0

您可以在開始時指定列名的數組:

$columns = array('warehouse', 'product'); 

然後你可以使用這些列的每個零件:查詢,標題和正文行。

// Return Results 
$sql = 'SELECT ' . implode(', ', $columns) . ' FROM table1'; 
$stmt = sqlsrv_query($conn, $sql); 

// Create table head 
echo '<table><thead><tr>'; 
foreach ($columns as $column) { 
    echo '<th>' . ucfirst($column) . '</th>'; 
} 

echo '</tr></thead><tbody>'; 

// Create table body 
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { 
    echo '<tr>'; 
    foreach ($columns as $column) { 
     echo '<td>' . htmlspecialchars($row[$column]) . '</td>'; 
    } 
    echo '</tr>'; 
} 
echo '</tbody></table>'; 

sqlsrv_free_stmt($stmt);