Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zoltiecodes's avatar

How to get the PDOStatement object from the Query Builder?

Hi.

How can I access the PDOStatement object when I'm using the Query Builder in Laravel?

Thanks.

0 likes
5 replies
Nakov's avatar

I don't think that there is such a thing as a PDOStatement. PDO is more like data access layer and it stands for PHP Data objects. So you can get a reference to the PDO through the connection:

DB::connection()->getPdo();

or if you want to write a statement you can use:

DB::connection()->statement()

here is the definition of the statement function:

/**
* Execute an SQL statement and return the boolean result.
*
* @param  string  $query
* @param  array   $bindings
* @return bool
*/
public function statement($query, $bindings = []);
Nakov's avatar

@ZSOLTGYURE - Can you share a code that you are trying to use so I can try to help better. If you open the Connection class, you can see this code:

/**
     * Configure the PDO prepared statement.
     *
     * @param  \PDOStatement  $statement
     * @return \PDOStatement
     */
    protected function prepared(PDOStatement $statement)
    {
        $statement->setFetchMode($this->fetchMode);

        $this->event(new Events\StatementPrepared(
            $this, $statement
        ));

        return $statement;
    }

Which you cannot access directly but you can set a listener for the Events\StatementPrepared event, and the PDOStatement will be given to you on which you can then use closeCursor().

1 like
zoltiecodes's avatar

@NAKOV - Well that event may be helpful, I'm gonna check that. Thanks.

So my exact problem is the following: There are SQL queries in the database and I need to run those, and return the results, but I get the following error:

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. (SQL: PREPARE stmt0 FROM @hhh;)

So I figured out I need to use the closeCursor() function. I also tried to add this to the mysql connection configuration array:

    'options'   => [
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
    ],

But this did not work.

jlrdw's avatar

Have you tried to

dd(DB::getQueryLog());

or

your query builder query->toSql();

Please or to participate in this conversation.