Nick0989
Nick0989

Reputation: 459

SQL formatting table data

I have a select query that pulls all the data from the database but it displays it like so:

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

I'm trying to get it to display like this:

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

But I have more than one row of data...So I'm not sure where i'm going wrong. Here's my query and echo statement.

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";
    } 
}

As you can see I kind of started to do a tr/th/td but i got lost...I assume maybe I need to echo out everything like....

echo table echo tr echo th ...but then i get lost right here because this would echo a label again...

Upvotes: 0

Views: 26

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

You should display the header only once:

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>";
}

Upvotes: 1

RainDev
RainDev

Reputation: 1128

try something like this:

<?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";
} 
}

Upvotes: 1

Related Questions