2015-10-25 61 views
0

我已經編寫了代碼,它將根據查詢的結果集動態生成一個表。每行中的每個字段都放在它自己的單元格中。如何將列名作爲標題添加到適當的列上?從數據庫獲取名稱列上面的表

我的代碼:

$db = new mysqli("...", "...", "", "..."); 
$query = "SELECT * from customer "; 
if ($result = $db->query($query)) { 

    /* Get field information for all columns */ 
    while ($finfo = $result->fetch_field()) { 
     printf("%s\n", $finfo->name); 
    } 
    $result->close(); 
} 


$db = new mysqli('...', '...', '...', '...'); 
if($db->connect_errno > 0){ 
    die('Unable to connect to database [' . $db->connect_error . ']'); 
} 
$sql = "SELECT * from ..."; 
if(!$result = $db->query($sql)){ 
    die('There was an error running the query [' . $db->error . ']'); 
} 
echo "<table class='table'>"; 
while($row = $result->fetch_assoc()){ 
echo "<tr class='info'> 
       <td>" . $row['COLUMN1'] . "</td> 
       <td>" . $row['COLUMN2'] . "</td> 
       <td>" . $row['COLUMN3'] . "</td> 
       <td>" . $row['COLUMN4'] . "</td> 
       <td>" . $row['COLUMN5'] . "</td> 
       <td>" . $row['COLUMN6'] . "</td> 
      </tr>"; 
} 
echo "</table>"; 

?> 

enter image description here

------------圖片問題解決了-------------

enter image description here

+0

您是否試圖顯示整列? –

+1

你的循環內只有4個'​​',而在你的圖像中有6列? – Akshay

+0

使用'SELECT * from customer'來獲取列名是非常糟糕的。至少在查詢上添加一個LIMIT 1。 – Ray

回答

1

您應該只需要打開1個數據庫連接。您可以在運行的查詢上使用fetch_field,而無需遍歷結果集的行。我要添加的所有空白都是可選的。

$db = new mysqli("...", "...", "", "..."); 

    if($db->connect_errno > 0){ 
     die('Unable to connect to database [' . $db->connect_error . ']'); 
    } 


    $sql = "SELECT * from ..."; 
    if(!$result = $db->query($sql)){ 
     die('There was an error running the query [' . $db->error . ']'); 
    } 

    echo " 
<table class='table'> 
    <thead> 
     <tr>"; 
    /* Get field information for all columns */ 
    while ($finfo = $result->fetch_field()) { 
     echo " 
     <th>" . $finfo->name . "</th>"; 
    } 
    echo " 
     </tr> 
    </thead> 
    <tbody>"; 
    while($row = $result->fetch_assoc()){ 
    echo "<tr class='info'> 
      <td>" . $row['COLUMN1'] . "</td> 
      <td>" . $row['COLUMN2'] . "</td> 
      <td>" . $row['COLUMN3'] . "</td> 
      <td>" . $row['COLUMN4'] . "</td> 
     </tr>"; 
    } 
    echo " 
    </tbody> 
</table>"; 
+0

您的解決方案工作正常。感謝指出我應該只使用一個連接。此外,我從來沒有想過以這種方式格式化表格。好的提示!我上傳了第二張圖片來實現你的代碼。現在試着修復它,讓它100%完美。 – gigi

+0

@吉吉實際上,看起來問題來自'id'列。既然你使用'SELECT *','fetch_fields'就會提取並顯示它,儘管你只想顯示其他6列。如果你不在任何地方使用'id'列,最簡單的解決方案是將'SELECT *'改爲'SELECT name,mail,number,price,paymentType,pcname' – Terminus

+0

我會試試你的解決方案,idid添加了id代碼中的列並更新了圖片解決方案。似乎沒有解決這個問題,但我正在關注這可能有所幫助。 http://stackoverflow.com/questions/11678298/centering-text-in-a-table-in-twitter-bootstrap – gigi