Hussam Adil
Hussam Adil

Reputation: 540

Illegal string PDO fetch() vs fetchAll()

When I try to call fetch() after executing a PDO statement, I get the following warning:

Warning: Illegal string offset

It works perfectly when I use fetchAll(), though.

What's the difference between the two, and how would I use either one?

$allData = $con->prepare("SELECT * FROM users");
$allData->execute();
$result = $allData->fetch();

Upvotes: 2

Views: 718

Answers (1)

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

This error is not due to the use of fetch() OR fetchAll() as neither of these functions are using an offset, there must be something you are doing in your code later that is causing this issue.

I believe your issue has to do with the way you are looping through your values as you say that it works when you use fetchAll(). Your loop is throwing an error because it is trying to access an offset that does not exist because fetch() will only return a single result while fetchAll() will return multiple from your query.


As for your question "What's the difference between the two (fetch() & fetchAll()), and how would I use either one?", here is your answer.

fetchAll() is used to return all relevant rows, according to the query.

This is beneficial for queries where you need many rows of data.

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch, or FALSE on failure.


fetch() is used to return a single row of results from your query.

This is beneficial for queries where you only need a single row result. This is useful for things like when a user logs in so you don't have to loop through data to assign it to variables.

Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.

Upvotes: 4

Related Questions