Best Practices: when to make the db connection?

I’ve programmed in other languages but am quite the noob in PHP. So I see a lot of tutorials and tips about putting the database connection code into a separate file that you include at the start of all your scripts. If you’re doing an insert, the logic looks like this:


include (dbconnect.inc)
if formSubmitted = yes
  validateData
  if no validationError
    insertRecord
  .
.
HTML FORM GOES HERE

But that means that the script connects to the database over and over, even when no record is inserted. Shouldn’t the database connection happen closer to when the database is actually accessed? I’m thinking like this:


if formSubmitted = yes
  validateData
  if no validationError
    include (dbconnect.inc)
    insertRecord
  .
.
HTML FORM GOES HERE

That way, if the user is just refreshing the screen or clicking OK without entering data, the script isn’t hitting the server with request after request.

Thanks for both answers. They clarified the issue for me.

It really depends where you need the database connection to run, if you have multiple functions on one page that all request a database connection then usually you would include it before all the functions and global the database connection $link

Conceptually if delaying the connection is your concern you could delay it until its needed. The general stance is that establishing or at least setting up the database connection is done in the programs initiation phase before any routing and outside templates.

(pseudo code)


<?php
class DB {

	private
	
	$_user
	,$_pass
	,$_db
	,$_host
	,$_connected = false;

	public function __construct($user,$pass,$db,$host) {
		$this->_user = $user;
		$this->_pass = $pass;
		$this->_db = $db;
		$this->_host = $host;
	}
	
	private function _connect() {
		/*
		* Connect to db and set connection to true if established otherwise error out
		*
		*/
		
		...
	}
	
	public function query($sql) {
	
		if($this->_connected === false) {
			$this->_connect();
		}
		
		...
	
	}

}

$db = new DB($user,$pass,$db,$host);

...

$db->query(...);
?>