How To Connect To And Query A PostgreSQL Database Using PHP And The pg Extension

PHP code example that demonstrates how to connect to and query a PostgreSQL database using the pg extension:

<?php
// PostgreSQL database credentials
$host = 'localhost';
$port = 5432;
$dbname = 'mydatabase';
$user = 'myusername';
$password = 'mypassword';

// Connect to PostgreSQL database
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");

// Check if the connection is successful
if (!$conn) {
  die('Connection failed: ' . pg_last_error());
}

// Execute a query to fetch data from a table
$query = "SELECT * FROM mytable";
$result = pg_query($conn, $query);

// Check if the query is successful
if (!$result) {
  die('Query failed: ' . pg_last_error());
}

// Loop through the query result and display data
while ($row = pg_fetch_assoc($result)) {
  echo $row['column1'] . ' ' . $row['column2'] . "<br>";
}

// Execute a query to insert data into a table
$query = "INSERT INTO mytable (column1, column2) VALUES ('value1', 'value2')";
$result = pg_query($conn, $query);

// Check if the query is successful
if (!$result) {
  die('Query failed: ' . pg_last_error());
}

// Close the database connection
pg_close($conn);
?>

Leave a Reply

Proudly powered by WordPress | Theme: Code Blog by Crimson Themes.