Close PDO statement

10,221

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.

Share:
10,221
dimlucas
Author by

dimlucas

Check my blog at https://www.dimlucas.com/ Making courses at: https://www.packtpub.com/eu/authors/dimitris-loukas

Updated on June 04, 2022

Comments

  • dimlucas
    dimlucas almost 2 years

    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?

  • oldboy
    oldboy over 4 years
    how come when i try to $pdo->close() i get "call to undefined method PDOStatement::close()"??