Understanding PDOStatement::fetch() Fetch Styles in PHP
This article explains the PDOStatement::fetch() method in PHP, detailing the available fetch style constants, their effects on result set formatting, and shows how to configure the statement to return only associative arrays for cleaner data handling.
The PDOStatement::fetch([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] ) : mixed method retrieves the next row from a result set according to the specified fetch style.
The $fetch_style argument must be one of the PDO::FETCH_* constants, each defining a different way to structure the returned data:
PDO::FETCH_ASSOC : returns an array indexed by column name.
PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0‑based column number.
PDO::FETCH_BOUND : returns TRUE and binds column values to PHP variables defined with PDOStatement::bindColumn() .
PDO::FETCH_CLASS : creates a new instance of a requested class, mapping column names to class properties; if combined with PDO::FETCH_CLASSTYPE , the class name is taken from the first column.
PDO::FETCH_INTO : updates an existing class instance with column values.
PDO::FETCH_LAZY : combines PDO::FETCH_BOTH and PDO::FETCH_OBJ , providing both array and object access.
PDO::FETCH_NUM : returns an array indexed by 0‑based column numbers only.
PDO::FETCH_OBJ : returns an anonymous object with properties named after column names.
When using the default fetch() call, the result contains both associative and numeric indexes, which may appear as duplicate data in debugging output.
To obtain a clean result set indexed solely by column names, set the fetch mode explicitly before fetching rows:
<code>$statement->setFetchMode(PDO::FETCH_ASSOC);</code>After this configuration, each call to fetch() will return an associative array, simplifying data handling in PHP applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.