-1

What happens when a script with following code is included into another php script, does it create a new PDO object every time..?? If yes, then how can i use a single PDO object created once throughout multiple php scripts..?? I don't want to use persistent connections..

try{    
    $dsn        =   'mysql:host=localhost;dbname=test'; 
    $username   =   'user';
    $password   =   'password'; 
    $conn = new PDO($dsn, $username, $password);
    $conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e) {
    echo 'ERROR: '. $e->getMessage();
}
000
  • 3,976
  • 4
  • 25
  • 39

3 Answers3

1

The script will create a new PDO object and will assign it to the variable $conn. Regarding this part, "how can i use a single PDO object created once throughout multiple php scripts" the answer is that you can reuse the $conn variable as many times as you want in each HTTP request. You must create (at least) one PDO object for each request (web page). If you want to use the object in several different PHP scripts, all of which are part of a single web page, you might want to put $conn into the $GLOBALS variable so it will be available in all scopes and namespaces.

Pankit Kapadia
  • 1,579
  • 13
  • 25
Ray Paseur
  • 2,106
  • 2
  • 13
  • 18
1

You could use a singleton database object throughout your script however there are some drawbacks to that approach so you might want to research "dependency injection".

In order to avoid repetition take a look at What is dependency injection? for more info on dependency injection.

Community
  • 1
  • 1
0

You can start like this:

if (!isset($conn)) {
  /* Create connection, copy your code */
}

But you should check if $conn is valid, too.
And it is not a bad idea to use a more specific variable name than $conn (like $global_pdo_connection) so it doesn't get mixed up with another $conneventually.

Imanuel
  • 3,596
  • 4
  • 24
  • 46