How to close a database connection using PDO?

Asked

Viewed 1,839 times

3

I’m new to PHP development and my app uses a method to open a database connection in Mysql, I am wanting to update and display the records.

I need to use some method to close the connection, like: function close()?

public function ($)
    {
        $sql  = "";
        try
        {
            $stmt = connectionDB::prepare($sql);
            if($stmt->execute())
            {
            }
        } catch (PDOException $e){
            echo "Err ->" . $e->getMessage();
        }

        finally{
             try {
                 $stmt = connectionDB::close();
             }
        }
}

My class:

class ClassDao extends Dao {

    public function insert($registro)
    {
        $sql  = "INSERT INTO table () VALUES ()";
        try
        {
            $stmt = connectionDB::prepare($sql);
            if($stmt->execute())
            {
                echo "INSERT!!";
            }
        } catch (PDOException $e){
            echo "Err ->" . $e->getMessage();
        }

    }

    public function update($registro)
    {
        $sql  = "UPDATE table SET var = :var, WHERE var = :var";
        try
        {
            $stmt = connectionDB::prepare($sql);
            if($stmt->execute()){
                echo "UPDATE!!";
            }
        } catch (PDOException $e){
            echo "Err ->" . $e->getMessage();
        }
    }

    public function findAll()
    {
        $sql = "SELECT * FROM table";
        try
        {
            $stmt = connectionDB::prepare($sql);
            if($stmt->execute()){
                return $stmt->fetchAll(PDO::FETCH_CLASS,'table');
            }
            else {
                return new Class();
            }
        } catch (PDOException $e){
            echo "Err ->" . $e->getMessage();
        }
    }

    public function createObject($r)
    {
        try{
            $var= new Class($r['var1'], $r['var2']);
            return $var;
        } catch (PDOException $e){
            echo "Err ->" . $e->getMessage();   
        }
    }
}

1 answer

6


$pdo = null;

You can use as in the above example more is not mandatory use as the connection is automatically closed after running the script.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.