2

This is my array:

When I used mysqli_query in a different script, this style worked:

while ($printTest = mysqli_fetch_array($results)) {
    echo $printTest['id'] . "<br />"; 
    echo $printTest['questions'] . "<br />";
    echo $printTest['answers'] . "<br />";
}

I can't figure out how to do the same thing with a PDO created array. With PDO, I can use foreach, like this:

foreach ($queryRows as $test=>questions){
    echo $test; 
}

Unfortunately, that doesn't give me access to id and answers in the same loop - which is important to me.

This is how I'm getting my PDO-generated array, currently:

$queryRows = $this->dbh->query("SELECT id, questions, answers FROM qarows WHERE usr = '$this->username'");
$queryRows = $queryRows->fetchAll(PDO::FETCH_ASSOC);

How do I access all 3 columns of my array, in a loop?

1
  • what is echo $test; outputting on each iteration? Commented Nov 10, 2014 at 7:52

1 Answer 1

2

It's still the same fetch rows from db. Its still the same multi dimensional structure:

$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/>'; 
}

Or the look a like 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 />";
}
Sign up to request clarification or add additional context in comments.

1 Comment

I feel like an idiot, I thought I had already tried what you said in the first code. Maybe I typed it wrong.. Thank you, Ghost.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.