MySQL,PHP:按类别拆分输出表

时间:2016-05-17 14:34:28

标签: php mysql database mysqli pdo

大家好, 我有一个问题,我希望有人可以帮助我。

我的MySQL数据库如下所示:

database

我想以这种方式在表格中输出这些数据:

output

我的实际代码如下:

<html>
<body>
<table>

<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/config.php";

$stmt = $pdo->prepare('SELECT * FROM TestTable ORDER BY name');
$stmt->execute();


$results = $stmt->fetchAll();


if (empty($results)) {
    echo 'Error!'; 
} else {
foreach( $results as $row ) {
        echo
        "
        <tr>
        <td class=\"left\">".$row['name']."</td>
        <td class=\"right\">".$row['address']."</td>
        </tr>
        ";
}
}

?>
</table>
</body>
</html>

输出看起来像这样:

actual output

如果专业的名称不一样,那么将职业的名称放在首位怎么办呢?

为了解决这个问题,我有这段代码:

<?php
$mysqli = new mysqli(host,username,password,db_name);

$sql = "SELECT * FROM TestTable ORDER BY profession, name";
$array = [];
$html = "";

    if ($result = $mysqli->query($sql)) {
        while($row = $result->fetch_assoc()) {
            if (!isset($array[$row['profession']])) {
                $array[$row['profession']] = array();
            }
            $array[$row['profession']][] = $row['name'];
        }
    }



foreach ($array as $profession => $name) {
    $html .= '<p style="font-weight:bold">'.$profession.'</p>';
    foreach ($name as $name) {
        $html .= '<p class="name">'.$name.'</p>';
    }
}
echo $html;

?>

output with second code

但我也需要这张桌子上的街道。我需要这个代码与PDO而不是MySQLi。我试图管理这个,但没有成功。

有人可以帮帮我吗?

问候, 大卫。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

$stmt = $pdo->prepare('SELECT * FROM TestTable ORDER BY profession, name');
$stmt->execute();

$results = $stmt->fetchAll();

if (empty($results)) {
   echo 'Error!'; 
} else {
$profession = $row['profession'];
foreach( $results as $row ) {
  if ($row['profession'] <>$profession) {
       echo "<tr><td>". $row['profession']."</td></tr>";
     }
    echo "<tr>
    <td class=\"left\">".$row['name']."</td>
    <td class=\"right\">".$row['address']."</td>
    </tr>
    ";
   $profession = $row['profession'];
}
}