1

I cant figure out why i only get 1 entry in the returning array, when the table has 4 entries in total.

My PDO code is:

$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
$katarray=$stmtkat->fetch(PDO::FETCH_ASSOC);
var_dump($katarray);

The return array i get:

 array(2) { ["id"]=> string(1) "1" ["kategorie"]=> string(12) "Coaching" }

The table has 4 rows, why do i get only the first row into the array? What i am doing wrong? Obviously i am new to PDO.

Ty for your time.

1
  • That gives me the data output: Array ( [id] => 1 [kategorie] => Coaching ) Commented Apr 4, 2016 at 14:40

2 Answers 2

4

You are only fetching one of the result rows produced by your query

If you use ->fetch() to get result rows one at a time you do it in a while loop like this

$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
while ( $katarray=$stmtkat->fetch(PDO::FETCH_ASSOC) ) {
    var_dump($katarray);
}

Or use fetchAll() to return all rows into a local array from a single call to the PDO Stmt object

$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
$katarray=$stmtkat->fetchAll(PDO::FETCH_ASSOC) ) {

var_dump($katarray);
Sign up to request clarification or add additional context in comments.

3 Comments

was just about to comment you could mention fetchAll as well, +1 :)
@JimL Yup that occured to me only when I realised he had called the variable $katarray. Thanks for the nudge
Thanks, that did it :)
2

You get only one row in return because:

PDOStatement::fetch — Fetches the next row from a result set

Use fetchAll() instead to get full array() of result or use fetch() inside while() loop.

Example with fetch() and while():

while ($stmtkat->fetch(PDO::FETCH_ASSOC)) {
  var_dump($katarray);
}

Example with fetchAll():

$result = $stmtkat->fetchAll(PDO::FETCH_ASSOC)
var_dup($result);

1 Comment

Thank you too, that was it.

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.