Home » Php » php – When should I use closeCursor() for PDO statements?

php – When should I use closeCursor() for PDO statements?

Posted by: admin April 23, 2020 Leave a comment

Questions:

The PHP documentation on closeCursor() says that it

frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.

When I have used the command though it doesn’t seem to matter if it is there or not in between my query statements, and I am beginning to wonder if I need it at all.

Is it different to use it for database calls that don’t return data vs. those that do?

How to&Answers:

This depends on the driver used. I think for mysql this will do nothing else than clear the result of the statement. After calling closeCursor() you cannot call fetch() anymore.
However executing the statement again should not be a problem.
Try to look at mysql_free_result(), it does a similar thing.

Answer:

To answer the question for MySql

As mentioned by N.B. before you execute() the same prepared PDOStatement.

EG: (this is bad practice but simple example, normally you would fetchAll or JOIN.
More complex scripts, such as with nested queries (see above about JOINs), makes this example more viable)

<?php
$ids = array( 1, 2 );
$sth = $pdo->prepare( "SELECT name FROM company WHERE id = :id" );
foreach( $ids as $id ) {
  $sth->execute( array( ':id' => $id ) );
  $result = $sth->fetch( PDO::FETCH_ASSOC );
  $sth->closeCursor();
  echo $result['name'] . PHP_EOL;
}
unset( $result );
$sth = null;
$pdo = null;
?>

As well specific to MySQL you can also optionally set the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute to false, which requires PHP to always check the database and would not need to closeCursor.
http://php.net/manual/en/mysqlinfo.concepts.buffering.php