What best practices should be followed when retrieving and displaying data from a MySQL database using PHP, especially in a loop?

When retrieving and displaying data from a MySQL database using PHP, especially in a loop, it is important to use prepared statements to prevent SQL injection attacks. This involves binding parameters to the query instead of directly inserting user input. Additionally, make sure to properly sanitize and validate any user input before using it in a query to avoid security vulnerabilities.

// 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);
}

// Prepare and execute a query using prepared statements
$stmt = $conn->prepare("SELECT id, name FROM table WHERE category = ?");
$category = "example_category";
$stmt->bind_param("s", $category);
$stmt->execute();
$result = $stmt->get_result();

// Display data in a loop
while ($row = $result->fetch_assoc()) {
    echo "ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
}

// Close connection
$stmt->close();
$conn->close();