【问题标题】:Query with a JOIN table not returning any result使用 JOIN 表查询不返回任何结果
【发布时间】:2013-12-24 03:11:30
【问题描述】:

您知道为什么我的查询在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();
    }

?>

谢谢

【问题讨论】:

  • 你正在获取一个关联数组;但使用对象语法来获取值。试试$res['name']

标签: php sql postgresql pdo


【解决方案1】:

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

...

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

...

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 2018-05-28
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    相关资源
    最近更新 更多