pdo -- lastInsertId cannot coexist with fetchAll

I've tried to create a php class to handle my database.  "table.class.php" is meant to query the db and produce tables, dropdowns and sundry other stuff.

This code will not fetchAll if lastInsertId exists in the function.  

What am I missing?

      protected function doQuery($sql, $fetchAll = false, $getColumnNames = false, $getInsertedId = false) {
            try {
                  $db = database::getInstance();
                  if(!$q = $db->query($sql)) {
                        throw new Exception('doQuery', 'empty resultset', $sql);
                  }      
                  // update class vars ...
                  $this->rowsAffected = $q->rowCount();
                  if($getInsertedId)
                        $this->id = $q->lastInsertId(); // *** remove this line for fetchAll to work ***
                  if($getColumnNames)
                        $this->fields = $q->fetch(PDO::FETCH_OBJ); // column names ...
                  if($fetchAll) {
                        return $q->fetchAll(PDO::FETCH_ASSOC);
                  }
                  $q->closeCursor(); // don't forget! ...
            }
            catch (PDOException $e) {
                  $msg = ($e->getMessage()) ? $e->getMessage() : 'database error';
                  $this->logIt('doQuery', $msg, $sql);
            }
      }
Glen GibbOwnerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
"lastInsertId" doesn't make any sense with a 'fetch'.  "lastInsertId" only returns meaningful data after an INSERT operation.  Even then it only works with the current connection.  It doesn't return anything you did yesterday.
0
Ray PaseurCommented:
I think you might want to take this back to the drawing board.  There are ways of doing these things that may give you a better chance of success if you map the familiar but obsolete MySQL functions onto PDO one at a time.  This article can help with that.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

A couple of examples of why I say that...

$db = database::getInstance(); is a singleton, which is a code smell. You cannot mock it for testing.  It's just another way of saying "global" instead of coding to the interface.  We don't do that any more.

if(!$q = $db->query($sql)) { throw new Exception('doQuery', 'empty resultset', $sql); would seem to suggest that the query engine returns FALSE if the results set is empty, but that is not right.  The query engine returns FALSE when the query fails.  There is a stark difference between a successful query that found no data, and a query that failed.  In the former instance, the programming was correct and the data contained noting to match the query ("find all the orange shoes in my closet").  In the latter, the query was malformed, meaningless, and could not be processed at all ("plud gort urst wsut ibbly in my closet").

You might want to think about separate methods for different query actions.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Glen GibbOwnerAuthor Commented:
Thanks.  Looks like I'll need separate query functions.

I thought that opening the db inside the function kept that instance LOCAL.  My db connection is in a different class.  

Am I totally off base here, too?
0
Ray PaseurCommented:
totally off base here, too?
Not totally, but you have to know how PHP object-oriented programming works.  There is a difference between variables and references.  If you come from the procedural programming world, you probably think that this creates a new variable, assigning the contents of $b to $a:

$a = $b;

And you would be right if $b is not an object.  If $b is an object, the "assignment" statement creates a pointer in $a that points to the $b object.

If it helps to understand the Singleton design pattern, here is my demonstration script.  You can run it to see what it is doing.

<?php // demo/oop_database_singleton.php
error_reporting(E_ALL);


// SINGLETON DATA BASE CONNECTION CLASS
class Database
{
    // CLASS PROPERTIES ARE ALL PRIVATE
    private static $connection;
    private static $instance;

    // CONNECTION VALUES (PROVIDE YOUR OWN)
    const DB_HOST = '?';
    const DB_USER = '?';
    const DB_PASS = '?';
    const DB_NAME = '?';

    // NULLIFY THE CLONE AND THE WAKEUP
    final private function __clone() {}
    final private function __wakeup() {}

    // OUR ONLY PUBLIC METHOD RETURNS THE CONNECTION
    public static function getConnection()
    {
        if (!self::$instance) self::$instance = new self();
        return self::$connection;
    }

    // CONSTRUCTOR CREATES THE CONNECTION
    private function __construct()
    {
        self::$connection
        = new mysqli
        ( self::DB_HOST
        , self::DB_USER
        , self::DB_PASS
        , self::DB_NAME
        )
        ;
        if (self::$connection->connect_error)
        {
            trigger_error(self::$connection->connect_error, E_USER_ERROR);
        }
    }
}


// SHOW WHAT HAPPENS WHEN YOU TRY TO MAKE TWO CONNECTIONS
$dbc_1 = database::getConnection();
$dbc_2 = database::getConnection();


// PROVE THAT THESE ARE THE SAME OBJECT http://php.net/manual/en/language.oop5.object-comparison.php
if ($dbc_1 === $dbc_2) echo 'EQUAL';

// SHOW THE OBJECT
var_dump($dbc_2);

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.