簡體   English   中英

如何使用PHP將數據寫入多個HTML表列?

[英]How to write data into multiple HTML table columns with PHP?

我使這段代碼將數據寫入HTML表:

<?php
//DB Verbindung
$con = mysqli_connect("localhost","root","","altislife");
$header = -1;
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM players";

if ($result=mysqli_query($con,$sql))
{
  echo "<thead><tr>";
  while ($fieldinfo=mysqli_fetch_field($result))
  {
    echo "<th>$fieldinfo->name</th>";
    $header++;
    echo "$header";
  }
  echo "</tr></thead>";
  mysqli_free_result($result);
}

if ($result=mysqli_query($con,$sql))
{
  echo "<tbody>";
  for ($i=0; $i < $header; $i++) {
    while($sql = mysqli_fetch_array($result))
    {
        echo "<tr><td>" . $sql[$i] . "</td><td> ";
    }
  }
  echo "</tbody>";
}

mysqli_close($con);

問題在於它僅填充第一列。

然后我嘗試了這個:

<?php
//DB Verbindung
$con = mysqli_connect("localhost","root","","altislife");
$header = -1;
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM players";

if ($result=mysqli_query($con,$sql))
{
  echo "<thead><tr>";
  while ($fieldinfo=mysqli_fetch_field($result))
  {
    echo "<th>$fieldinfo->name</th>";
    $header++;
    echo "$header";
  }
  echo "</tr></thead>";
  mysqli_free_result($result);
}

if ($result=mysqli_query($con,$sql))
{
  echo "<tbody>";
  while($sql = mysqli_fetch_array($result))
  {
    for ($i=0; $i < $header; $i++) {
      echo "<tr><td>" . $sql[$i] . "</td><td> ";
    }
  }
  echo "</tbody>";
}

mysqli_close($con);

此代碼的問題與第一個示例相同。 誰能看到我的錯誤?

if ($result=mysqli_query($con,$sql))
{
    $row = mysqli_fetch_assoc($result);
    $html = '<table><tr><th>'.implode('</th><th>',array_keys($row)).'</th></tr>';
    do {
       $html .= '<tr><td>'.implode('</td><td>',$row).'</td></tr>';
    }while($row = mysqli_fetch_assoc($result));
    $html .='</table>';
}
echo $html;

這樣嘗試,並弄清楚它是如何工作的;-)

指向您的代碼:

  • tbody不是table 您的第一個示例沒有表格標簽
  • 在表中的行與定義<tr></tr> 你的第二個例子錯過了結束標記
  • theadtbody是可選的,對html沒有影響

最后一點:不必運行sql兩次以生成表

implode($sep,$arr) implode像<th></th>一樣接受了args和分隔符,並將數組的所有條目合並為: array('a','b','c')變成a<th></th>b<th></th>c

mysqli_fetch_assocmysqli_fetch_array秒給出類似[0=>'a',1=>'b']和第一個['name'=>'a','color'=>'b']

您需要獲取數據庫中的整個記錄​​,而不僅僅是一個字段。 嘗試fetch_assoc(請參閱http://www.w3schools.com/php/php_mysql_select.asp )。

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM