Search code examples
phpobjectpdoresultset

Clone a PDOStatement


For debug purpose, I would like to be able to clone a PDOStatement, or fetch data without removing the rows from the statement.

Here's an example to show what I'm trying to do :

public function execute($query)
{
    // Prepare the statement
    if (!($stmt = $this->prepare($query))) {
        return false;
    }

    // Execute the statement
    $stmt->execute($params);

    // Print the query with a custom debug tool
    if( $config->debug ) {
        Debug::print($query);
        Debug::print($stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    // Return the PDOStatement
    return $stmt;
}

The problem is that fetchAll() do its job, remove every result from my statement, and an empty array is returned by the function.

I'm searching a way to print the query result (debug purpose) and return the initial statement (treatments purpose), without querying my database twice !

I tried to clone my statement, without success :

if( $config->debug ) {
    $_stmt = clone $stmt;
    Debug::print($query);
    Debug::print($_stmt->fetchAll(PDO::FETCH_ASSOC));
}

Any idea ?


Solution

  • PDOStatement is not cloneable.

    The only way to achieve what I wanted was to re-execute the statement:

    public function execute($query)
    {
        // Prepare the statement
        if (!($stmt = $this->prepare($query))) {
            return false;
        }
    
        // Execute the statement
        $stmt->execute($params);
    
        // Print the query with a custom debug tool
        if( $config->debug ) {
            Debug::print($query);
            Debug::print($stmt->fetchAll(PDO::FETCH_ASSOC));
            $stmt->execute($params);
        }
    
        // Return the PDOStatement
        return $stmt;
    }