Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 304
  • Last Modified:

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);
            }
      }
0
Glen Gibb
Asked:
Glen Gibb
  • 2
1 Solution
 
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
 
Glen GibbAuthor 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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now