-1

I outputed the data from my database in a HTML Table and styled it with CSS. Everything is fine, but there is an awkward White space above the outputed Table. (see picture). What's wrong with my code?

Result: enter image description here

<html>
<head>
<title>Create new user</title>
<style>
table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  text-align: left;
  padding: 8px;
}

tr:nth-child(even){background-color: #f2f2f2}

th {
  background-color: #4CAF50;
  color: white;
}
</style>
</head>
<body>

<div>
<?php


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "users";

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

$sql = "select * from employee";
$result = $conn->query($sql);

 echo "<table>";
 echo "<th>Identifier</th><th>Name</th><th>Lastname</th>";
if ($result->num_rows > 0) {
       
    while($row = $result->fetch_assoc()) {

  echo "<tr>";
  echo "<td>" . $row["id"] . "</td>";
     echo "<td>" . $row["vorname"] . "</td>";
  echo "<td>" . $row["nachname"] . "</td>";
  echo "</tr>";
  echo "</br>";
 
    }
 
}
else {
    echo "0 results";
}
echo "</table>";

$conn->close();

?>
</div>
</body>
</html>

Expected result : no white space above the Table

Many Thanks

Muhammad Bilal
  • 2,106
  • 1
  • 15
  • 24
anyname
  • 103
  • 1
  • 11
  • 4
    Open `Inspect Element` and see what is there? – Muhammad Bilal Jan 02 '19 at 11:38
  • Also remove this space (between php start tag and your first variable). – PrakashG Jan 02 '19 at 11:40
  • Not related to your question, but your code can be improved to ease the maintenance. Start with a [DOCTYPE](https://stackoverflow.com/questions/14613030/do-i-need-a-doctype-declaration-in-a-php-file-with-html). Also try not to mix presentation with code. Your PHP presentation logic (the HTML output) is only expecting an array. Make your array aviable before starting the HTML. Then you can simply your PHP presentation code. – mTorres Jan 02 '19 at 11:41

1 Answers1

0

Why are you adding a <br>

echo "</br>";

in your while loop.

Try this -

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {

        echo "<tr>";
        echo "<td>" . $row["id"] . "</td>";
        echo "<td>" . $row["vorname"] . "</td>";
        echo "<td>" . $row["nachname"] . "</td>";
        echo "</tr>";
    }

} else {
    echo "0 results";
}

If this does not fix, try inspecting and see what is adding space. Also check for the padding and margins in the computed view in chrome inspect view.

If nothing works, try setting top:0 for the div and may be for table :)

Ravi Kumar Gupta
  • 1,698
  • 2
  • 22
  • 38
  • Yes it did the trick! it was indeed the Tag, it was inside the loop! But again, it should'nt make w white space above the table! awkward! but thanks, it worked! – anyname Jan 02 '19 at 11:57