How can the PHP code be modified to ensure that all pages display the table data correctly?

The issue is likely due to incorrect database connection or query execution, resulting in empty or incorrect table data being displayed. To solve this, ensure that the database connection is established correctly and that the query is executed successfully to fetch the table data. Additionally, check for any errors in the query syntax or table structure that may be causing the issue.

<?php
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch table data
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Display table data
if ($result->num_rows > 0) {
    echo "<table><tr><th>Column 1</th><th>Column 2</th></tr>";
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["column1"] . "</td><td>" . $row["column2"] . "</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

$conn->close();
?>