2013-09-24 26 views
2

我試圖創造一些像下面這樣:創建多行表使用MySQL

但我當前的代碼給我:

的白色部分是我用下面的代碼得到的,而黑色部分是我在添加兩個<td>行時得到的。問題是我無法獲得每行3個數據創建 - 只能垂直或水平。

$result = mysqli_query($con,"SELECT * FROM show_listing"); 
while($row = mysqli_fetch_array($result)) 
{ 

echo "<table> 

<tr> 
<td>".$row['name']."'</td> 
</tr> 

</table>"; 
} 

mysqli_close($con); 

它可能比我想象的更簡單,但有人知道我該怎麼做到這一點?

+0

只要有可能,請使用文本而不是圖形。 – tadman

回答

1
$c = 0; 
echo "<table>"; 
while($row = mysqli_fetch_array($result)) 
{ 
    if ($c%3 == 0) { 
     if ($c) echo "</tr>"; 
     echo "<tr>"; 
    } 
    echo "<td>".$row['name']."</td>"; 

    $c++; 
} 
if ($c) echo "</tr>"; 
echo "</table>"; 
0

你有正確的想法。您不希望在while循環中聲明,結果是您將獲得多個表。

所以我將表格聲明移到了while循環之外。我也根據當前的專欄做出了有條件的聲明。您現在可以將變量$列設置爲所需的多列。

$result = mysqli_query($con,"SELECT * FROM show_listing"); 
echo "<table>" 
$columns=3; 
$current_column=1; 
while($row = mysqli_fetch_array($result)) 
{ 

if($current_column==1) { 
    echo "<tr>"; 
} 

echo "<td>".$row['name']."'</td>"; 

if($current_column==$columns) { 
    echo "</tr>"; 
    $current_column=1; 
} else 
    $current_column++; 
} 
echo "</table> 

mysqli_close($con);