Are there any best practices for optimizing PHP code that involves querying a database and storing results in an array?

When querying a database and storing results in an array in PHP, it is important to optimize the code for performance. One way to improve efficiency is to minimize the number of queries executed and reduce unnecessary data retrieval. Additionally, using prepared statements can help prevent SQL injection attacks and improve security.

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare the SQL query
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE column = :value");

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

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

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

// Loop through the results
foreach ($results as $row) {
    // Do something with the data
}

// Close the database connection
$pdo = null;