What are the best practices for integrating PHP with PostgreSQL for efficient data retrieval and manipulation?

To integrate PHP with PostgreSQL for efficient data retrieval and manipulation, it is recommended to use prepared statements to prevent SQL injection attacks, utilize indexes on frequently queried columns to improve performance, and consider using stored procedures for complex data manipulation tasks.

<?php
// Connect to PostgreSQL database
$host = 'localhost';
$port = '5432';
$dbname = 'mydatabase';
$user = 'myuser';
$password = 'mypassword';
$dsn = "pgsql:host=$host;port=$port;dbname=$dbname;user=$user;password=$password";
$pdo = new PDO($dsn);

// Prepare and execute a SELECT query using a prepared statement
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE column = :value');
$stmt->execute(['value' => 'myvalue']);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Use the retrieved data as needed
foreach ($results as $row) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}
?>