簡體   English   中英

將數據回顯到表中的特定列

[英]Echo data to specific column in table

我正在使用for循環為SQL查詢的結果生成表。 我正在嘗試更改代碼,以便將新文本回顯到表的特定列中(第8列)

$fields_num = mysql_num_fields($result);

echo "<h1>Table: {$table}</h1>";
echo "<table border='0' id=resultTable><tr>";


for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($result);
    echo "<td id" . $i;
    echo "></td>";
}

echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

    echo "</tr>\n";
}
mysql_free_result($result);
?>

“我正在嘗試更改代碼,以便將新文本回顯到表的特定列”中的“新文本”實際上是什么意思?

“文本”是特定表字段的名稱嗎? 如果是這樣,最好更改正在使用的mysql_query中字段的順序,而不要為此在html生成中進行任何更改

例如

SELECT field1, field2, ... new_text from ... 

new_text放在第八位。

更新資料
如果要在結果表中的各個列中顯示各種內容,則可以放置一個計數器,並按如下所示進行所需的操作:

// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    $counter = 0;
    foreach($row as $cell)
    {
        if($counter == 7)
        {//eighth column
            echo "<td><img src='".$cell."' /></td>";
        }
        else if($counter == 5)
        {//sixth col
            echo //something else ...
        }
        else
            echo "<td>$cell</td>";
            //inside your default td
        $counter++;
    }

    echo "</tr>\n";
}

但是具有一些配置數組將更易讀,可維護且可自定義,您可以在其中指定哪一列將保存如下內容:

function getColumnConfigs()
{
   return $columnsConfigs = array(5=> "something_else", 7 => "img");
   //specify special cases for necessary columns. columns not mentioned here will take default.
}

然后在迭代中使用它:

 // printing table rows
$columnsConfig = getColumnConfigs();
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    $counter = 0;
    foreach($row as $cell)
    {
        if(isset($columnsConfig[$counter]))
        {
            switch($columnsConfig[$counter])
            {
                 case "img":
                              $html = "<td><img src='".$cell."' /></td>";
                              break;
                 case "something_else"
                              $html = "<td><img src='".$cell."' /></td>";
                              break;
            } 
        }
        else
        {//default
            $html = echo "<td>$cell</td>";
        }

    }

    echo "</tr>\n";
}

暫無
暫無

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

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