Are there specific best practices for handling PostgreSQL connections in PHP scripts?
When handling PostgreSQL connections in PHP scripts, it is important to establish a connection only when needed and close it when done to prevent resource leaks. It is also recommended to use prepared statements to prevent SQL injection attacks and improve performance.
<?php
// Establish a connection to the PostgreSQL database
$host = 'localhost';
$port = '5432';
$dbname = 'mydatabase';
$user = 'myuser';
$password = 'mypassword';
$dsn = "pgsql:host=$host;port=$port;dbname=$dbname;user=$user;password=$password";
try {
$pdo = new PDO($dsn);
// Use prepared statements for queries
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE id = :id');
$stmt->execute(['id' => 1]);
$result = $stmt->fetchAll();
// Close the connection when done
$pdo = null;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>