下面是我的代码块
</tr>
<tr>
<td bgcolor="aabbcc"><center>Line 1</td>
<?php
//Connect to mysql server
$con = mysqli_connect('localhost', 'User', 'Pass', 'Database');
if (!$con) {
die ("connection error". mysqli_connect_error());
}
$results = mysqli_query($con, " SELECT * FROM PMAsset where LineNum='1' Order by Linenum, LineOrder ") or die(mysqli_error($con));
while($row = mysqli_fetch_array($results)) {
?>
<td Bgcolor=<?php echo $row['PMStatus']?>>Line <?php echo $row['LineNum']?> PM <?php echo $row['LineOrder']?></td>
<?php
}
?>
</tr>我正在尝试做的是创建一个表格行,填充数据有10列,我附加了一张我目前得到的图片。

正如你所看到的,它并没有循环10次。我需要做些什么才能做到这一点。我对构建循环感到困惑。图片中的3号线应该在3号线PM3下。我理解为什么它是这样的。但是,如果没有数据可用,如何将其放入正确的单元格中并将框改为黑色?任何帮助都是最好的。这是数据库表

<center>
<table border="1" Width="80%">
<tr bgcolor="5DF588">
<th>Line Number</th>
<th>PM 1</th>
<th>PM 2</th>
<th>PM 3</th>
<th>PM 4</th>
<th>PM 5</th>
<th>PM 6</th>
<th>PM 7</th>
<th>PM 8</th>
<th>PM 9</th>
<th>PM 10</th>
</tr>
<tr>
<td bgcolor="aabbcc"><center>Line 1</td>
<td Bgcolor=Red>Line 1 PM 1</td>
<td Bgcolor=green>Line 1 PM 2</td>
<td Bgcolor=Yellow>Line 1 PM 3</td>
<td Bgcolor=Green>Line 1 PM 4</td>
</tr>
<tr>
<td bgcolor="E5F29D"><center>Line 2</td>
<td Bgcolor=Red>Line 2 PM 2</td>
</tr>
<tr>
<td bgcolor="aabbcc"><center>Line 3</td>
<td Bgcolor=Yellow>Line 3 PM 3</td>
</tr>发布于 2017-08-08 02:41:06
哦,我明白了,为什么不创建一个函数,您可以将行号和行序传递给它,然后针对给定的行号和行序运行查询。因此,该函数可以从数据库返回null或值,您可以通过循环通过for循环来使用它来填充单元格。
函数可以是这样的:
function getcell($linenumber, $lineorder){
global $con;
$r = mysqli_query($con, "SELECT * FROM PMAsset where LineNum='$linenumber' AND `LineOrder` = '$lineorder' LIMIT 1") or die(mysqli_error($con));
if( $r->num_rows == 1){
$row = $r->fetch_assoc();
return '<td> ... HTML HERE .. </td>';
} else {
return '<td> </td>';
}
}您可以使用嵌套的for循环遍历每个linenum和lineorder,以获得更好的控制。希望这能有所帮助。
发布于 2017-08-08 02:49:27
你需要知道你已经输出了多少个元素,并用剩余的插槽填充它。
$col = 0;
while($row = mysqli_fetch_array($results)) {
?>
<td Bgcolor=<?php echo $row['PMStatus']?>>Line <?php echo $row['LineNum']?> PM <?php echo $row['LineOrder']?></td>
<?php
$col++;
}
while ($col++ < 10) {
echo '<td />';
}发布于 2017-08-08 02:55:18
我认为你可以采用另一种方法。您可以尝试将所有数据保存在一个二维数组中,然后对其进行循环。
将数据保存在二维数组中:
// your new array
$data = [];
$sql = "
SELECT * FROM PMAsset
ORDER BY Linenum, LineOrder
;";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while( $row = mysqli_fetch_array( $result ) ) {
// use the LineNum and LineOrder as Keys
$data[ $row[LineNum] ][ $row[LineOrder] ] = $row['PMStatus'];
}现在,您已经拥有了10列和10行的数组和cana循环中的完整数据:
... your table head
// loop LINENUMBERS -> $ln
for( $ln = 1; $ln < 10; $ln++ ) {
// loop LineOrder -> $lo
for( $lo = 1; $lo < 10; $lo++ ) {
echo "<tr>";
if( isset( $data[$ln][$lo] ) {
// key exists and is not empty or NULL
echo "<td Bgcolor=\"{$data[$ln][$lo]}\"> Line {$ln} PM {$lo} </td>";
} else {
// key does not exists
echo "<td>no data</td>";
}
}
echo "</tr>";
}
...希望代码是清晰的。让我知道。
https://stackoverflow.com/questions/45553223
复制相似问题