SQL格式化表格数据

时间:2018-07-08 01:46:52

标签: php sql

我有一个选择查询,该查询从数据库中提取所有数据,但显示方式如下:

First name: Jasmine
Last name: Santiago
Address: 123 Butt street
City: Butt hill
Customer ID: 12

我正试图让它像这样显示:

First name:   Last name:  Address:          City:       Customer ID:
Jasmine       Santiago    123 Butt street   Butt hill   12
with          more        rows              here of just the data not the labels

但是我有不止一行数据...所以我不确定我要去哪里。这是我的查询和回显语句。

if(isset($_POST["get-user-info"])) {
    $user_info_sql = "SELECT * from customer_info";
    $user_info_result = $conn->query($user_info_sql);

    if ($user_info_result->num_rows > 0) {
        while($row = mysqli_fetch_assoc($user_info_result)) {
            echo "<tr><th>First name: </th>" . $row["First_name"]. "</tr></br>" . "<tr>Last name: " . $row["Last_name"] . "</tr></br>" . "<tr>Address: " . $row["Address"]. "</tr></br> " . "<tr>City: " . $row["City"] . "</tr></br>" . "Customer ID: " . $row["Customer_id"] . "</br>" . "</br></br>";
        } 
    } else {
        echo "No results found";
    } 
}

您可以看到我有点开始做tr / th / td了,但是我迷路了...我想也许我需要回声像......

回声表 回声tr 回声 ...但是后来我迷路了,因为这会再次呼应标签...

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

<?php 
if(isset($_POST["get-user-info"])) {
$user_info_sql = "SELECT * from customer_info";
$user_info_result = $conn->query($user_info_sql);

if ($user_info_result->num_rows > 0) {
  echo "<tr><th>First name: </th><th>Last name:</th><th>Address:</th><th>City:</th><th>Customer ID:</th></tr>";
    while($row = mysqli_fetch_assoc($user_info_result)) {
        echo "<tr><td>". $row["First_name"]."</td><td>" . $row["Last_name"] . "</td><td>" . $row["Address"]. "<td></td>" . $row["City"] . "<td></td>" . $row["Customer_id"] . "</td></tr>";
    } 
} else {
    echo "No results found";
} 
}

答案 1 :(得分:1)

您应该只显示一次标题:

if ($user_info_result->num_rows > 0) {
    // display table header
    echo "<table><tr><th>First name: </th><th>Last name: </th><th>Address: </th><th>City: </th><th>Customer ID: </th></tr>";
    while($row = mysqli_fetch_assoc($user_info_result)) {
        echo "<tr><td>". $row["First_name"]. "</td>" .
             "<td>". $row["Last_name"]. "</td>" .
             "<td>". $row["Address"]. "</td>" .
             "<td>". $row["City"]. "</td>" .
             "<td>". $row["Customer_id"]. "</td></tr>";
    }
    echo "</table>";
}