Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close PDO statement

I recently decided to make the big jump from MySQLi to PDO and there's something bothering me regarding PDO's prepared statements.

In MySQLi I would write a typical fetch query like this:

$db = new mysqli("localhost", "user", "pass", "mydb");
$sql = "SELECT firstCol, secondCol FROM testTable WHERE thirdCol=?";
$stmt = $db->prepare($sql);
$stmt->bind_param("s", $thirdCol);
$stmt->execute();
while( ($row = $stmt->fetch()) )
{
   //do something
}
$stmt->close();
$db->close();

with the appropriate error checking of course. After the query I always close the statement and the database connection. When using PDO I close the connection by setting the database handler to null like so:

$db = null;

But what about the statement? I found a post here that suggests either the use of unset or closeCursor . Which one is better? Should I just set it to null like the connection?

like image 716
dimlucas Avatar asked Sep 27 '15 15:09

dimlucas


1 Answers

with the appropriate error checking of course.

I am sure that error checking were not nearly appropriate. To check for errors, you have to set just single mysqli configuration option (as well as PDO) and leave particular queries execution alone.

After the query I always close the statement and the database connection.

Speaking of database connection, in case you had to run more than one query in the same script, you did it utterly wrong. As you had to open connection again to run another query, which slows your application with no reason.

When using PDO I close the connection by setting the database handler to null

Just like with mysqli, if you're closing it right at the script's end, it's ok, but unnecessary. But if you're closing it after every query, that's wrong!

You have to connect only once, and than use that single connection variable all the way through.

As of statements, it's up to you. Most of time statement variable gets overwritten, which makes previous instance set to null. When you call a function, all its variables are set to null when function ends. When php script ends, all it's variables are set to null again. Thus, there is nothing to worry about as a rule.

like image 181
Your Common Sense Avatar answered Sep 29 '22 10:09

Your Common Sense