php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #42664 PDO::FETCH_CLASSTYPE is not useful for abstracting code.
Submitted: 2007-09-13 18:37 UTC Modified: 2011-02-21 21:01 UTC
Votes:4
Avg. Score:4.5 ± 0.9
Reproduced:2 of 3 (66.7%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: jdriddle_producer at yahoo dot como Assigned:
Status: Open Package: PDO related
PHP Version: 5.2.4 OS: *
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2007-09-13 18:37 UTC] jdriddle_producer at yahoo dot como
Description:
------------
Currently, the PDO::FETCH_CLASSTYPE option is used with PDO::FETCH_CLASS in $result->fetch() in order to create an object based upon a classname determined by data in the table. Unfortunately, the method looks for the FIRST COLUMN in the result. This is counter to common relational database design.

The only way to currently work around this and get at the desired functionality is to abandon the common 'SELECT * from $tableName' construct that is so useful in abstraction, and use custom 'SELECT classType, col2,col3,... from _tableName_' for each query.

I suggest that the PDO::FETCH_CLASSTYPE option be changed to take an optional parameter, $colName, for the column name to look for the class name in. The current behavior would remain as the default. 

This would allow:
$objArray = [];
$query = "SELECT * from $tableName";
$result = $dbh->query($query);
$count = $result->rowCount();
for($i=0;$i<$count;$i+=1)
{
    $objArray[] = $result->fetch(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE,"classType");
}

Or similar construct.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-09-13 19:29 UTC] jdriddle_producer at yahoo dot como
After additional thought, it might be better to add this functionality to PDOStatement->fetchObject() instead. That way there would be no chance of mucking up PDOStatement-> fetch() with the added parameters.
 [2011-02-21 21:01 UTC] jani@php.net
-Package: Feature/Change Request +Package: PDO related -Operating System: all +Operating System: *
 [2011-09-12 21:09 UTC] restlesslythought at gmail dot com
You actually don't have to list out all the column names. You can just use * 
again.

This works perfectly:

$query = "SELECT `classType`, `$tableName`.* from $tableName";
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Thu Jun 20 20:01:27 2019 UTC