Difference between fetch and setFetchDP methods

Asked

Viewed 555 times

6

I understood the difference between fetch and fetchAll, but now, what is the difference between those and setFetchMode? Looks like it’s the same thing... (at least when it comes to riding).

I can do both like this:

fetch(PDO::FETCH_ASSOC);

and

setFetchMode(PDO::FETCH_ASSOC);

2 answers

4

Optionally fetch() and fetchAll() may have the default format changed by passing the respective constant as argument. Its advantage is to use a format other than the standard at a specific point in the code without it interfering with other parts.

setFetchMode() defines directly in Pdostatement the default format of return ie all calls from fetch()/fetchAll() will obey this setting.

Another way to define the default format is through the constructor stating a value for ATTR_DEFAULT_FETCH_MODE as in the example below:

$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ)
$db = new PDO('mysql:host=localhost;dbname=vendas;', 'root', '', $options);

The same result is obtained with the method setAttribute()

3

In PDO, the method setFetchMode is used to define how the data is obtained, in the case of the example you posted, the constant PDO::ASSOC is used to return the data in an associative array.

The methods fetch/fetchAll with the parameter PDO::ASSOC will obtain the data of a query in an associative array (because it uses the constant in question), in which case the method itself is specifying directly how the data will be returned. Generally, this is only necessary when the PDO has not previously been configured with the setFetchMode.

In case a return type is configured with setFetchMode, the parameter passed to the fetch/fetchAll is no longer precise. That is, the method setFetchMode lets configured the standard way to get the data so you don’t have to specify it later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.