2015-10-25 27 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