Search code examples
phppostgresqlphp-pgsqlpg-query

pg_query throwing an error


I'm trying to get data from a postgresql database, I get the error: pg_last_error() expects parameter 1 to be resource, object given in /path/to/query.php So the data is as an object not a resource. Any ideas how to fix this?

The SQL works with this code:

foreach ($conn->query($sql1) as $row) 
{
print $row["Site_ID"] . " ";
print $row["Site_name_1"] . "<br /> ";

}

But the problem arrises when I use pg_query instead.
Here's my code:

<?php include 'header.php'; ?> 
<div class='container'> 
<?php include 'menu.php'; ?>
<?php include 'PDO_connect.php'; ?>

<?php

$sql1='SELECT "Site_ID", "Site_name_1" FROM "Sites" ORDER BY "Sites"."Site_ID" ASC'; 

$result1 = pg_query($conn,$sql1);
if(!$result1) {
    echo "There is an error!";
    echo pg_last_error($conn);
}
?>

My connection info

<?php
try {
$dbuser = 'usr';
$dbpass = 'pwd';
$host = "localhost";
$dbname="db";

$conn = new PDO('pgsql:host=localhost;dbname=db', $dbuser, $dbpass);
}catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
?>

Solution

  • As said in the comments I was mixing PDO and pg_connect, this solves my problems:

    <?php
    $servername = "localhost"; 
    $username = "usr"; 
    $password = "pwd";
    $database = "db";
    ?>
    
    <?php
        $conn = pg_connect("host=localhost dbname=$database user=$username password=$password")or die("Can't connect to database".pg_last_error());
    ?>