2

Hi I've got a page where I can view data output from a mysql database. It works good. But it's not stylish. So I decided to put in a html <table> tag. However it's not displaying the data.

I've tried putting in

<td> </td> etc between rows but it stops the code being parsed.

<?php
    $servername = "******";
    $username = "root";
    $password = "********";
    $dbname = "test2";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT first_name, last_name, email FROM person_list";
    $result = $conn->query($sql);



    //display table
    echo "<table border='1'>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Email</th>
    </tr>";

           if ($result->num_rows > 0) {
         // output data of each row

         while($row = $result->fetch_assoc()) {
           echo
     "<br>   ". $row["first_name"]. " "
                                   . $row["last_name"] ." "
                                    . $row["email"] ." " ;
        }
    }
     else {
         echo "0 results";
    }

    echo "</table>";
    $conn->close();
    ?>
1
  • 1
    You don't need to use the '<br>' tag, each '<tr>' (table row), will make a new row. You've declared three columns (th) in your header, so the body of your table need to have three columns too. Try Narendra Sisodia answer, it's correct. Commented Mar 9, 2015 at 13:35

2 Answers 2

3

Try this one, if it works for you..

echo "<table border='1'>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Email</th>
    </tr>";

       if ($result->num_rows > 0) {
     // output data of each row

     while($row = $result->fetch_assoc()) {
       echo "<tr>";
       echo "<td>". $row["first_name"] . "</td>";
       echo "<td>". $row["last_name"] . "</td>";
       echo "<td>". $row["email"] . "</td> " ;
       echo "</tr>";
    }
}
echo "</table>";
Sign up to request clarification or add additional context in comments.

Comments

0

You might also be intrested in the foreach way.

Foreach would be quicker in larger data sets, but this is very similar to Narendrasingh Sisodia answer.

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>";
if($result->num_rows > 0){
    foreach($result as $row){
        echo "<tr>";
        echo "<td>". $row["first_name"] . "</td>";
        echo "<td>". $row["last_name"] . "</td>";
        echo "<td>". $row["email"] . "</td> " ;
        echo "</tr>";
     }
}
echo "</table>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.