In mysqli, fetch
is a method or function that is applied to the mysqli_stmt
and that serves to read the results returned by said object. fetch
could be translated in Spanish as go to search , or bring , recover . This is what makes fetch
in essence, bring us the results obtained.
Generally fetch
is used within a loop ( while, foreach
), because in a certain sense this method what is done is to place a pointer in the obtained results, starting with the first record, and then go through them row by row .
That's why fetch
is almost always used in this way:
/* obtener los valores */
while ($sentencia->fetch()) {
printf ("%s (%s)\n", $nombre, $código);
}
Derived methods of fetch
The link that you put in your question (which points to the different variants of fetch
in PDO), opens the door for us to talk about other methods derived from fetch
that exist in mysqli
.
As much as PDO (although this allows many more possibilities and more interesting), mysqli
you have several methods that we could call variants of fetch
, which allow us to bring the results in a certain way according to the later use that we want to give to said results.
It must be said that fetch
is only applicable to the object mysqli_stmt
, as we said above. While these other methods can also be applied to the mysqli_result
object, to bring / read the results that return these objects 1 .
It is convenient to list these methods, we can find them in the Class Synopsis mysqli_result
, described in the PHP Manual .
They are the following:
-
fetch_all
: Get all rows in an array associative, numerical, or both.
-
fetch_array
: Get a row of results as a associative, numeric array, or both.
-
fetch_assoc
: Get a result row as a result associative array.
-
fetch_field_direct
: Get the metadata of a only field.
-
fetch_field
: Get the next resultset field.
-
fetch_fields
: Get an array of objects that represent the fields of a result set.
-
fetch_object
: Get the current row of a set of results as an object.
-
fetch_row
: Get a row of results as a array listed.
Not as rich as PDO , but, something is something :) In addition, it should be noted that in mysqli
, for some of these methods to work, it is necessary to have installed the driver mysqlnd
, which is an added difficulty, which makes mysqli
less attractive (at least for me), since you will be programming code that in part may not work, depending on an external driver. For me it is a serious mistake of the designers of mysqli.
I hope it serves you.
Notes:
1 fetch
on the contrary, it is not applicable to the object mysqli_result
. When we try to read the results returned by this object using fetch
, we have the following exception: Call to undefined method mysqli_result::fetch()
. Note that this is applicable for the mysqli_query
method, which is usually used when there is no need for queries prepared and whose result is also an object mysqli_result
.