PHP查询结果从一列到多列

时间:2010-09-28 18:49:41

标签: php mysql html-table

// Database Settings 
define('DB_HOST', '******');
define('DB_PORT', '******');
define('DB_USER', '******');
define('DB_PASS', '******');
define('DB_NAME', '******');

// Connection to Database
$database = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT);

$sql = 'SELECT AManufactureBrand.brand, AManufactureModel.model, AManufactureEdition.edition'
        . ' FROM AManufactureModel'
        . ' INNER JOIN AManufactureBrand ON AManufactureModel.brand_id = AManufactureBrand.brand_id'
        . ' INNER JOIN AManufactureEdition ON AManufactureModel.model_id = AManufactureEdition.model_id'
        . ' WHERE AManufactureEdition.edition=\'345i\'';

$resultSet = $database->query($sql);

// Begin building some HTML output

$html = '<table border="0">
<tr>
<th>Editions</th>
</tr>';

while ($row = $resultSet->fetch_assoc())
{
$html .= '<tr><td>' . $row['brand'] . '</td></tr>';
$html .= '<tr><td>' . $row['model'] . '</td></tr>';
$html .= '<tr><td>' . $row['edition'] . '</td></tr>';
}

$html .= '</table>';

echo $html;
?>

例如这个查询调用了BMW 3Series 345i,我有两个来自mysql打印的结果 到我网站上的表格。两个记录在一列上打印出来的问题 起。

目前我在我的网页上得到一个这样的结果,两个mysql记录垂直向下打印一列。


我正试图让它像这样穿过,并在彼此横向打印多辆汽车。

2 个答案:

答案 0 :(得分:2)

不确定你要做什么,但我建议更换一下:

// Begin building some HTML output

$html = '<table border="0">
<tr>
<th>Editions</th>
</tr>';

while ($row = $resultSet->fetch_assoc())
{
$html .= '<tr><td>' . $row['brand'] . '</td></tr>';
$html .= '<tr><td>' . $row['model'] . '</td></tr>';
$html .= '<tr><td>' . $row['edition'] . '</td></tr>';
}

$html .= '</table>';

用这个:

// Begin building some HTML output

$html = '<table border="0">
<tr>
<th>Brand</th>
<th>Model</th>
<th>Edition</th>
</tr>\n';

while ($row = $resultSet->fetch_assoc())
{
$html .= '<tr>';
$html .= '<td>' . htmlentities($row['brand']) . '</td>';
$html .= '<td>' . htmlentities($row['model']) . '</td>';
$html .= '<td>' . htmlentities($row['edition']) . '</td>';
$html .= '</tr>\n';
}

$html .= '</table>';

这将为您提供正确的3列输出。如果这不是您想要的,那么请澄清您的问题。

答案 1 :(得分:1)

我知道用HTML做更好的方法但这应该有效:

$ths = $tds1 = $tds2 = $tds3 = '';

while ($row = $resultSet->fetch_assoc())
{
$ths .= '<td>Editions</td>';
$tds1 .= '<td>' . $row['brand'] . '</td>';
$tds2 .= '<td>' . $row['model'] . '</td>';
$tds3 .= '<td>' . $row['edition'] . '</td>';
}

$html = "<table border="0">
<tr>$ths</tr>
<tr>$tds1</tr>
<tr>$tds2</tr>
<tr>$tds3</tr>
</table>
";

您也可以连续使用多个表。