Are there best practices for structuring PHP code to effectively output desired results based on database values?

When structuring PHP code to output desired results based on database values, it is important to follow best practices such as using prepared statements to prevent SQL injection, separating database logic from presentation logic, and using functions to modularize code for reusability and maintainability.

<?php
// Connect to the database
$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);
}

// Query the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Output results based on database values
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();
?>