这是我的阵列:
当我在不同的脚本中使用mysqli_query时,这种风格有效:
while ($printTest = mysqli_fetch_array($results)) {
echo $printTest['id'] . "<br />";
echo $printTest['questions'] . "<br />";
echo $printTest['answers'] . "<br />";
}
我无法弄清楚如何使用PDO创建的数组做同样的事情。使用PDO,我可以使用foreach,如下所示:
foreach ($queryRows as $test=>questions){
echo $test;
}
不幸的是,这不允许我在同一个循环中访问id
和answers
- 这对我很重要。
这就是我现在获取PDO生成的数组的方式:
$queryRows = $this->dbh->query("SELECT id, questions, answers FROM qarows WHERE usr = '$this->username'");
$queryRows = $queryRows->fetchAll(PDO::FETCH_ASSOC);
如何在循环中访问我的数组的所有3列?
答案 0 :(得分:2)
它仍然是来自db的相同提取行。它仍然是相同的多维结构:
$select = $this->dbh->prepare('SELECT id, questions, answers FROM qarows WHERE usr = :usr');
$select->bindParam(':usr', $this->username);
$select->execute();
$queryRows = $select->fetchAll(PDO::FETCH_ASSOC);
foreach ($queryRows as $questions){
echo $questions['id'] . '<br/>';
}
或者看起来像mysqli:
$select = $this->dbh->prepare('SELECT id, questions, answers FROM qarows WHERE usr = :usr');
$select->bindParam(':usr', $this->username);
$select->execute();
while($printTest = $select->fetch(PDO::FETCH_ASSOC)) {
echo $printTest['id'] . "<br />";
echo $printTest['questions'] . "<br />";
echo $printTest['answers'] . "<br />";
}