使用JOIN表查询而不返回任何结果

时间:2013-12-06 16:59:46

标签: php sql postgresql pdo

你知道为什么我的查询在echo res:之后没有返回任何值吗? (res:看似很好,但之后没有任何内容)。

我有一个名为Person的表和一个名为people_friends的JOIN表:

CREATE TABLE person (
  idperson integer primary key,
  name VARCHAR(50)
);
CREATE TABLE people_friends (
  person_id integer,
  otherPerson_id integer,
  primary key (person_id, otherPerson_id),
  FOREIGN KEY (person_id)
    REFERENCES person (idperson),
  FOREIGN KEY (otherPerson_id)
    REFERENCES person (idperson));

查询:

<?php
//CONNECT
    try {
        $connection = new PDO('pgsql:host='.$PARAM_host.';dbname='.$PARAM_db_name, $PARAM_user, $PARAM_password);    
        echo "test";
    }
catch(Exception $e)
    {
        echo 'Error : '.$e->getMessage().'<br />';
        echo 'N° : '.$e->getCode();
    }

//QUERY
    try {
        echo '<br/>qsdf<br/>';
        $q = "SELECT p.idperson, p.name FROM person p INNER JOIN people_friends pf ON p.idperson = pf.person_id";
        $res = $connection->query($q);
        $res->setFetchMode(PDO::FETCH_ASSOC);
        echo "res : ".$res->name;
    }
catch(Exception $e)
    {
        echo 'Error : '.$e->getMessage().'<br />';
        echo 'N° : '.$e->getCode();
    }

?>

由于

1 个答案:

答案 0 :(得分:1)

你错过了获取记录。它应该是:

...

$res->setFetchMode(PDO::FETCH_ASSOC);
while($record = $res->fetch()) {
    var_dump($record['name']);
}

...