在从MySQL数据库获取信息后,我正试图通过PHP将HTML表输出转换为特定格式。
在HTML中,我可以这样做:
<table cellpadding="0" cellspacing="0" class="list">
<tr>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name1'">Name1</td>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name2'">Name2</td>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name3'">Name3</td>
</tr>
<tr>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name4'">Name4</td>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name5'">Name5</td>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name6'">Name6</td>
</table>
这工作得很好,看起来也很好,我已经把它划分好了,格式也很好。
然而,我需要从MySQL中提取名称,然后在需要时创建一个新的单元格,然后在3个单元格之后创建一个新行。
到目前为止,我有这个:
<?php
//PRESENTERS HERE
/* connect to the db */
$connection = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($db, $connection);
/* show tables */
$result = mysql_query('SHOW TABLES', $connection) or die('cannot show tables');
echo '<h1>Presenters:</h1>';
while ($tableName = mysql_fetch_row($result))
{
$table = 'presenters';
/* Get the presenters*/
$result2 = mysql_query('SELECT presenter FROM ' . $table) or die('cannot show data from ' . $table);
}
if (mysql_num_rows($result2))
{
echo '<table cellpadding="0" cellspacing="0" class="list">';
while ($row1 = mysql_fetch_row($result2))
{
echo '<tr>';
foreach ($row1 as $key => $value)
{
echo '<td style="cursor:hand" onclick='"window.location.href = ''page.php?presenter=' . $value . '">', $value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
?>
但我不知道如何让它表现得像上面的HTML一样。我也无法让点击事件正常工作。
PHP表单的所有条目都在一行中,而不是三行一行。
啊,我看到你的问题是3行中的条目,而不是一行。
while($row1 = mysql_fetch_row($result2)) {
echo '<tr>';
foreach($row1 as $key=>$value) {
echo '<td style="cursor:hand" onclick='"window.location.href = ''page.php?presenter='.$value.'">',$value,'</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
因为每次从数据库中检索内容(while循环语句)时,都是在打开和关闭表中的行。
您需要在while循环之外启动一个计数器,该计数器计算您有多少行,当您达到所需的列数时,重置计数器并关闭表标记。
类似这样的东西:
$columncount = 0;
while($row1 = mysql_fetch_row($result2)){
if($columncount == 0){
echo "<tr>";
}
foreach($row1 as $key=>$value) {
echo '<td style="cursor:hand" onclick='"window.location.href = ''page.php?presenter='.$value.'">',$value,'</td>';
}
$coloumncount ++;
//assuming you want 3 columns in your table
if($columncount == 3) {
echo "</tr>";
$coloumncount = 0;
}
}
不会解决onclick事件,但它会格式化表。
祝你好运!
onclick
属性的第一个引号是否在此行中意外转义?
echo '<td style="cursor:hand" onclick='"window.location.href = ''page.php?presenter='.$value.'">',$value,'</td>';
您还在示例静态HTML和PHP示例中生成的HTML之间使用不同的CSS类(class="list"
与class="db-table"
)。