user6651317
user6651317

Reputation:

MySQL pdo select single column with limit but return one row

I'm trying to get the last 3 records from my table + only the titles column but I get only one result.

$query = $connect->prepare("SELECT title FROM tutorials LIMIT 3");
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) { echo $value; }

Is working if I use fetchAll but in my case I don't need all the columns, just the only one(title) so there is no sense using fetchall but why is returning only one row?

Upvotes: 0

Views: 1249

Answers (2)

spencer7593
spencer7593

Reputation: 108400

fetch retrieves one row, or it returns FALSE if there is no row to fetch. (We could do the processing in a loop, and fetch each "next row", until fetch returns FALSE.

  $query->execute();
  while ( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
     echo $row['title'];
  }

There's only one column in the resultset. It seems like we are confused about fetch and fetchAll.

http://php.net/manual/en/pdostatement.fetch.php

http://php.net/manual/en/pdostatement.fetchall.php


If we use fetchAll to retrieve all of the rows, we get an array back, each element in the array is a row from the resultset.

  $query->execute();
  if( $rs = $query->fetchAll(PDO::FETCH_ASSOC) ) {
     foreach($rs as $row) {
        echo $row['title'];
     }
  }

Upvotes: 4

Bill Karwin
Bill Karwin

Reputation: 562358

http://php.net/manual/en/pdostatement.fetch.php says:

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

It only fetches one row each time you call fetch(). You either need to call it in a loop until it reaches the end of your result set, or else use fetchAll().

It sounds like you are mixing up the terms "row" and "column" somehow.

Upvotes: 1

Related Questions