What best practices should be followed when retrieving multiple values from a database in PHP?

When retrieving multiple values from a database in PHP, it is best practice to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, fetching the data using a loop and storing it in an array or object can help manage and manipulate the results more easily.

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

// Prepare a SQL statement
$stmt = $pdo->prepare("SELECT column1, column2 FROM table_name WHERE condition = :condition");

// Bind parameter values
$condition = 'some_value';
$stmt->bindParam(':condition', $condition);

// Execute the statement
$stmt->execute();

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

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