What are some best practices for querying a database and displaying the results in PHP?

When querying a database and displaying the results in PHP, it is essential to use parameterized queries to prevent SQL injection attacks. Additionally, it is recommended to fetch the results into an associative array for easier manipulation and display. Finally, ensure to properly handle any errors that may occur during the query execution.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a parameterized query
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE column = :value');
$stmt->bindParam(':value', $value);
$stmt->execute();

// Fetch the results into an associative array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Display the results
foreach ($results as $row) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}