Home Illegal string PDO fetch() vs fetchAll()
Reply: 1

Illegal string PDO fetch() vs fetchAll()

Hussam Adil
1#
Hussam Adil Published in 2018-01-12 21:12:48Z

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();
GrumpyCrouton
2#
GrumpyCrouton Reply to 2018-01-12 21:35:04Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.265848 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO