What are some best practices for organizing and displaying data from a MySQL database in a PHP script?

When organizing and displaying data from a MySQL database in a PHP script, it is important to use proper coding practices to ensure efficiency and readability. One best practice is to separate your database logic from your presentation logic by using functions or classes to handle database queries and data manipulation. Additionally, consider using prepared statements to prevent SQL injection attacks and sanitize user input before executing queries. Finally, use HTML and CSS to format and style the data for a user-friendly display.

<?php
// Connect to MySQL 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 database for data
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

// Display data in HTML table
if ($result->num_rows > 0) {
    echo "<table>";
    echo "<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";
}

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