I would like to know what is the difference between fetch and fetchall in php, from what I saw there fetch returns a single field and fetchall all the fields, but using PDO it seems to me that it doesn't matter which one you use, I totally use it (PDO:: FETCH_ASSOC) , but I would still like to know the difference, thanks :)
It's two different things mixed up in the question:
fetch
opens as a pointer ready to iterate through the data one by one (usually via a loop
while
). It is the recommended method when a lot of data is expected, because that way you will not have memory problems.Code example:
Here
$datos
it will be an associative array that will be filled with a row each time the pointer advances inside thewhile
.Also, the data can be printed on site if it is not needed to transport it to another place:
fetchAll
fetches all the data at once , without opening any pointers, storing it in an array. It is recommended when not expecting too many results that could cause memory problems when trying to save thousands or millions of rows in an array at once! coming from
SELECT
aCode example:
In this case it
$resultado
is an associative array with all the query data. If you want to read the rows in it, you can implement a loop that goes through the array:It is almost the same as in
fetch
, only that here we are not acting on a traversal of the data through a pointer, but on the data already stored in a variable. If, for example, before this we close the statemente, we already have the data in it$resultado
and we can read it. Iffetch
we close the statement we will not be able to read the data.Looking at
PDO::FETCH_ASSOC
is just a way of representing the data. One of thosefetch_style
that exist, which indicates that you want the results in the form of an associative array where the key is the name of each column and the value is the data belonging to that column. You can use it both withfetch
and withfetchAll
.It should be noted that both for
fetch
and forfetchAll
the default style isPDO::FETCH_BOTH
. But you can set a default style to be to the connection object using the methodsetAttribute
, changing the value of the constantPDO::ATTR_DEFAULT_FETCH_MODE
; be to a specific statement using thesetFechMode
.