Solved

pdo -- lastInsertId cannot coexist with fetchAll

Posted on 2014-07-27
4
296 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 40223732
"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 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40223745
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
ID: 40224432
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 110

Expert Comment

by:Ray Paseur
ID: 40224639
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

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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 four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

615 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