Solved

pdo -- lastInsertId cannot coexist with fetchAll

Posted on 2014-07-27
4
273 Views
Last Modified: 2014-07-28
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
Comment
Question by:Glen Gibb
  • 2
4 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
"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
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
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
 

Author Closing Comment

by:Glen Gibb
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now