Difference between the fetch and setFetchMode methods of the PDO

Posted on

Coding Problem :

I’ve understood the difference between fetch and fetchAll, but now, what’s the difference between these and setFetchMode? It looks like it’s the same thing … (at the time of riding at least).

I can do both like this:

fetch(PDO::FETCH_ASSOC);

and

setFetchMode(PDO::FETCH_ASSOC);

    

asked by anonymous 16.08.2017 / 01:08

Answer :


Answer 1 :

Optionally fetch() and fetchAll() can have the return format changed from the defined pattern by passing its constant as argument. Its advantage is to use a format other than the default at a specific point in the code without interfering with other parts.

setFetchMode() sets PDOStatement the default return format ie all calls of fetch()/fetchAll() will obey this setting.

Another way to set the default format is through the constructor by reporting 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 using the setAttribute() method

    


Answer 2 :

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

The fetch/fetchAll methods with the PDO::ASSOC parameter will get 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 was not preconfigured with setFetchMode .

In case a return type is set with setFetchMode, the parameter passed to fetch / fetchAll is no longer accurate. That is, setFetchMode sets the default way to get the data so you do not have to specify it later.

    


Answer 3 :


Answer 4 :


Answer 5 :


Answer 6 :


Answer 7 :


Answer 8 :


Answer 9 :

Leave a Reply

Your email address will not be published.