当fetchAll工作时,PDO提取不起作用

时间:2016-01-11 22:08:51

标签: php pdo

我试图在我的网站上实现PDO,我正在检查fetch和fetchAll的使用,并发现了这种奇怪的行为。这段代码完美无缺:

    $query="SELECT `id`, `username`, `nome`, `email`, `pwd`, `level` FROM `users` WHERE `username`= ? LIMIT 1";
    $stmt=$myconn->prepare($query);
    $stmt->bindParam(1, $uname);
    $stmt->execute();

    $row=$stmt->fetchAll();
    print_r($row);

虽然这个不起作用:fetch返回false而没有错误代码(00000):

    $query="SELECT `id`, `username`, `nome`, `email`, `pwd`, `level` FROM `users` WHERE `username`= ? LIMIT 1";
    $stmt=$myconn->prepare($query);
    $stmt->bindParam(1, $uname);
    $stmt->execute();

    while($row = $stmt->fetch()) {
        echo $row->username . "\n";
        echo $row->nome . "\n";
        echo $row->email . "\n";
    }

知道为什么吗?

1 个答案:

答案 0 :(得分:1)

这应该有效:

$stmt=$myconn->prepare($query);
$stmt->bindParam(1, $uname);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);  
while($row = $stmt->fetch()) {
    echo $row['username'] . "\n";
    .        
    .
    .
}