如何使用PHP从PostgreSQL中获取数据

时间:2018-03-07 17:29:23

标签: php psql

我无法从PHP中获取PostgreSQL中的数据。每次运行查询时,它都会返回NULL。

我的查询:

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

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

1 个答案:

答案 0 :(得分:0)

看起来您的数据库连接存在问题。尝试使用pg_last_error()查看发生了什么。以下是一些例子:

<?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);
?>

使用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());
    }
?>