codrgi
codrgi

Reputation: 211

php database connection?

i have a few question on php db connection and hoping someone can answer them all, when i create a db connection using pdo, like below

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>
  1. is this connection always created when someone refreshes the php page?
  2. or does it check if that connection is already open and then use that connection instead?
  3. how would i be able to close that connection when i am done with it?

Upvotes: 1

Views: 412

Answers (2)

Matthew
Matthew

Reputation: 61

I found this in the php manual. Hope it helps.

To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Upvotes: 1

zerkms
zerkms

Reputation: 255155

  1. yes
  2. nope. It tries to utilize previously established connections only if you have set up permanent connections
  3. generally you don't need to do anything special. php does that as long as your script ends

Upvotes: 1

Related Questions