How can database results be effectively displayed in an HTML table using PHP?

When displaying database results in an HTML table using PHP, you can retrieve the data from the database, loop through the results, and then output each row as a table row (<tr>) with each column as a table data cell (<td>). This can be done by using PHP's database functions to query the database and fetch the results, and then using HTML code to structure the data into a table format.

&lt;?php
// Connect to database
$servername = &quot;localhost&quot;;
$username = &quot;username&quot;;
$password = &quot;password&quot;;
$dbname = &quot;database&quot;;

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

// Check connection
if ($conn-&gt;connect_error) {
    die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);
}

// Query database
$sql = &quot;SELECT * FROM table_name&quot;;
$result = $conn-&gt;query($sql);

// Display results in HTML table
echo &quot;&lt;table&gt;&quot;;
echo &quot;&lt;tr&gt;&lt;th&gt;Column 1&lt;/th&gt;&lt;th&gt;Column 2&lt;/th&gt;&lt;/tr&gt;&quot;;
if ($result-&gt;num_rows &gt; 0) {
    while($row = $result-&gt;fetch_assoc()) {
        echo &quot;&lt;tr&gt;&lt;td&gt;&quot; . $row[&#039;column1&#039;] . &quot;&lt;/td&gt;&lt;td&gt;&quot; . $row[&#039;column2&#039;] . &quot;&lt;/td&gt;&lt;/tr&gt;&quot;;
    }
} else {
    echo &quot;&lt;tr&gt;&lt;td colspan=&#039;2&#039;&gt;No results found&lt;/td&gt;&lt;/tr&gt;&quot;;
}
echo &quot;&lt;/table&gt;&quot;;

// Close connection
$conn-&gt;close();
?&gt;