PHP:“ - >”没有在mysql结果集上工作

时间:2014-03-10 15:56:12

标签: php mysql fetch

我有一种奇怪的行为。今天我一直在使用 - >从mysql结果集中检索成员变量,例如

$username = $result->user_name

但这在我目前的项目中没有用。

$sth = self::$dbConnection->prepare("SELECT user_id, user_name FROM users");                              
$sth->execute();
$result = $sth->fetch();

$test = $result->user_password_hash; // $test is null

$test = $result["user_password_hash"]; // this works

????

2 个答案:

答案 0 :(得分:4)

修复解析错误后,如果需要对象:

$result = $sth->fetch(PDO::FETCH_OBJ);

或者:

$result = $sth->fetchObject();

或者在使用fetch()之前设置模式:

$sth->setFetchMode(PDO::FETCH_OBJ);

答案 1 :(得分:1)

PDOStatement::fetch fetch()开始返回一个索引和关联的数组。箭头(->)用于访问对象属性(或方法)。要拥有和对象而不是数组,您可以改为调用fetch(PDO::FETCH_OBJ)