我使用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);
?>
答案 0 :(得分:0)
“我正在尝试更改代码,以便将新文本回显到表格的特定列中”中的“新文字”实际上是什么意思?
“text”是特定表字段的名称吗?如果是这样,最好改变你正在使用的mysql_query中的字段序列,而不是在html生成中对此进行任何更改
e.g。
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";
}