0

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();
}
?>
Spatial Digger
  • 1,883
  • 1
  • 19
  • 37
  • Can you show the declaration of `$conn`? You can check its value with var_dump($var). It should be a resource returned by pg_connect: http://php.net/manual/en/function.pg-connect.php – JSLirola Apr 16 '17 at 20:18
  • var_dump($conn) returns: object(PDO)#1 (0) { } – Spatial Digger Apr 16 '17 at 20:37
  • 1
    I think you are mixing PDO with pg_* methods, if you connect with PDO you should use [PDO functions](http://php.net/manual/en/class.pdo.php). Check this similar question: http://stackoverflow.com/questions/16108784/connect-to-postgresql-using-pdo – JSLirola Apr 16 '17 at 20:42
  • Ah, by using PDO I guess I can't use pg_query and the like, so if I connect using pg_connect then that should sort it out? Sorry for the noob error, I'm switching from mysql. – Spatial Digger Apr 16 '17 at 20:46

1 Answers1

0

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());
?>
Spatial Digger
  • 1,883
  • 1
  • 19
  • 37