sam scoot1900
sam scoot1900

Reputation: 45

How to fetch data from PostgreSQL using PHP

I am unable to fetch data from PostgreSQL in PHP. Every time I ran a query it returns NULL.

My query:

$psql = new psql('localhost','database','user','password');

$psq = pg_query("SELECT * FROM students");
$result = pg_fetch_row($psq);
var_dump($result); 

Upvotes: 4

Views: 13935

Answers (1)

Mateusz Kleinert
Mateusz Kleinert

Reputation: 1376

Looks like you have an issue with the database connection. Try to use pg_last_error() to see what is going on. Here are some examples:

<?php
    $dbhost = 'localhost';
    $dbname='database';
    $dbuser = 'user';
    $dbpass = 'password';

    $dbconn = pg_connect("host=$dbhost dbname=$dbname user=$dbuser password=$dbpass")
        or die('Could not connect: ' . pg_last_error());

    $query = 'SELECT * FROM students';
    $result = pg_query($query) or die('Error message: ' . pg_last_error());

    while ($row = pg_fetch_row($result)) {
        var_dump($row);
    }

    pg_free_result($result);
    pg_close($dbconn);
?>

And with PDO:

<?php
    try {
        $dbhost = 'localhost';
        $dbname='database';
        $dbuser = 'user';
        $dbpass = 'password';

        $connection = new PDO("pgsql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);

        $sql = 'SELECT * FROM students';

        foreach ($connection->query($sql) as $row) {
            var_dump($row);
        }

        $connection = null;
    } catch (PDOException $e) {
        die("Error message: " . $e->getMessage());
    }
?>

Upvotes: 4

Related Questions