0

There is something, as a newbie, that a I want to understand about About database connections.

I am starting off from a tutorial on PHP which has this structure:

Connect.php:

<?php 

$username = "dbusername"; 
$password = "dbpassword"; 
$host = "localhost"; 
$dbname = "dbname"; 
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

try 

{ 
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
} 
catch(PDOException $ex) 
{ 
    die("Failed to connect to the database: " . $ex->getMessage());  
} 

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 


header('Content-Type: text/html; charset=utf-8'); 

session_start(); 
?>

Login.php:

<?php
 require("connect.php");     
 // some code not important for this question, 
 //that handles login with a session…
?>

various_file_in_the_login_system.php:

 <?php
  require("connect.php");
  //  some code that checks  if user is logged in with session_ …
  // some code that does need the database connection to work
  ?>

All other files also contain that require("connect.php"); line. It works, but I just don’t know what these connection request to the server – I may not be using the right vocabulary -- end up doing to the server. They are superfluous if the connection is not timed out, are they not?

I found a post which talked about doing a singleton for PDO, and a post which makes me feel like never using persistent connections in my life.

Does this design causes excessive connection churning?

Perhaps servers can handle very many request for connection per second, perhaps a server has its own internal persistent connection mode, or implements connection pooling… Or the PDO object handle the problem of asking connection too often for no reason…

PDO + Singleton : Why using it?

What are the disadvantages of using persistent connection in PDO

Community
  • 1
  • 1
user762997
  • 35
  • 5

2 Answers2

1

This is what I can recommend for your database connection: Make a class for the connection:

class Database{
private static $link = null ;

public static function getConnection ( ) {
    if (self :: $link) {
        return self :: $link;
    }

    $dsn = "mysql:dbname=social_network;host=localhost";
    $user = "user";
    $password = "pass";

    self :: $link = new PDO($dsn, $user, $password);
    return self :: $link;
}

}

Then you can get the connection like this:

Database::getConnection();

The Singleton Pattern is hard to scale - However, I think it will probably be fine for your needs. It takes a lot of load off your database.

I don't think you will be able to avoid the multiple includes.

There is a php.ini setting for prepending a file to every script -> http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file

Patrick Geyer
  • 1,515
  • 13
  • 30
  • @user762997 - I'm not sure what you're suggesting by posting the link. With self I access static members of the class. – Patrick Geyer Jan 16 '14 at 21:01
  • If I understand well : **1** I was right to worry about the re-instanciation of PDO on each php file. **2** your proposal is a singleton. **3** No object Database have to be instanciated to call the method getConnection(); **4** if the connection had been lost, the PDO object $link was destroyed (??) and is re-instanciated , otherwise, if $link exist, it is returned -- and nothing is asked to the server. I rad this [link](http://stackoverflow.com/questions/151969/when-to-use-self-vs-this) ... my head hurts a little !! but if no one convinces me otherwise I will mark you as _answered_... – user762997 Jan 16 '14 at 21:21
  • 1 & 4 - If you create multiple classes, each relying on a connection it could exhaust the Database server. No object has to be instantiated to call `getConnection()` but the function will instantiate the Object itself - but only once, the first time you call it. It is then kept throughout the execution of the script and returned when it is next requested - this means you should only use 1 connection to Database server per client. 2 = Yes, it is a singleton pattern! – Patrick Geyer Jan 16 '14 at 21:27
  • @user762997 P.S.: The Singleton Pattern is taking a lot of (deserved?) abuse on Stackoverflow at the moment. It is not advised for larger scale applications. However, I think it's fine for you. If you notice that you need some control over your connections and classes I recommend looking into Other design patterns, (Especially factory) -> http://www.phptherightway.com/pages/Design-Patterns.html. They would allow you to create multiple connections (perhaps 3 or 4) that would share the load. – Patrick Geyer Jan 16 '14 at 21:30
  • @user762997 - referring to point #4 you made. I do not understand why the connection would be lost? The only reason I can think of this happening is if the client or server goes completely offline. Then it would not make a difference what object is returned. Or did I not correctly understand your question? Please do ask further questions if you need assistance! – Patrick Geyer Jan 16 '14 at 21:43
  • - at point 4, I am only thinking of cases where the server makes a "time out" on the connection. phpMyAdmin, for instance, disconnects if I am idle for too long, ftp connection behave the same way... Thank you very much for your prompt answer. With a very small webapp with at most 500 users, the singleton approach will do it for me... but I will do the reading on the link you are giving me here. – user762997 Jan 17 '14 at 01:11
  • @user762997 - I cannot give an opinion on the time out. I think this will have to do with when the browser stops communicating with the server as the connection to the database will then become idle. It will not disconnect if you are still interacting with the database though. -> If you're looking for ways to get instant data from the server without the connection going idle, I suggest looking into long and short polling. http://stackoverflow.com/questions/333664/simple-long-polling-example-code – Patrick Geyer Jan 17 '14 at 08:19
1

How about you change to

require_once('connect.php');

in all locations?

Also you should probably remove session_start() and HTTP header logic from a section of code that has to do with establishing a DB connection. This simply does not make sense there.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • I did my homework on this. The php manual is not explicit on what I am about to discuss : make test.php file : ` test home"; ?>

    test 2

    ` test2.php :` ` included.php : ` include code being run... "; ?>` . test2.php **will run** the included.php ... exactly what I don't want.
    – user762997 Jan 17 '14 at 03:03
  • @user762997 I don't think I understand your comment. It looks like test2.php is just linked from test.php. If so when you go to test2.php page, it is a totally different request being processed by PHP, it has no relation to test.php and thus the include would happen during the execution of this separate script. If you don't want the require on that page, then don't include it on that page.. – Mike Brant Jan 17 '14 at 05:03