opening database connection

is it ok to open a connection anywhere in a php script, eg if i’m collecting data from a form and only want to connect to the db if the form criteria is met. Currently i have the connection and query all taking place within an else statement. is this normal practice? or doesn’t it matter?

Generally, no. Your database connections should be in a single file, at a minimum the configuration ( connection details ) should be in a single file. The reason being, if anything changes in the connection string, location, username, password, added table columns, ect: you only have to update it in a single location. If those details are spread among several files, it becomes tedious to maintain the system.

ah ok. If it was wrapped in a function (in a separate file) and i made a function call in the location i mentioned (inside the else statement), would this be ok?

thanks

The Database connection string is usually in a configuration file of some sort (config.php, utilities.inc.php) where that file is put at the top of each php file.

For example I have this in my utilities.inc.php file:
[php]/* PDO Connection */
$db = new Connect;
$pdo = $db->getDatabase();[/php]

along with autoloader, but you would probably just have the db connection string in that file then all I have to do to use it on a page would be something like:
[php]function get_total_questions($pdo) {
$result = $pdo->query(“SELECT id FROM pictures WHERE id > 0”);

$total_pictures = $result->rowCount();  // Grab the current number of questions that is in the database table:

return $total_pictures;

}[/php]

this is kind of bad example for it uses a function within the php page file; however, if you notice I pass the $pdo string to the function.

Hope that clears it up a little bit more.

My example:

In use:
[php]
$db = new db();

$values = array(
‘:username’ => ‘jsmith’,
‘:password’ => hash(‘whirlpool’, ‘password’),
‘:fname’ => ‘James’,
‘:lname’ => ‘Smith’,
);
try {
$db->insertUser( $values );
} catch ( Exception $ex ) {
echo $ex->getMessage();
}
[/php]

The class itself:
[php]

<?php class db extends \PDO { public $pdo; public function __construct() { $this->pdo = new PDO('mysql:host=localhost; dbname=sample', 'root'); } public function insertUser( Array $params){ $placeholders = array( ':username', ':password', ':fname', ':lname' ); foreach ( $placeholders as $value ) { if ( !array_key_exists($value, $params) ) { throw new Exception("Missing parameter, '$value'"); } } $sql = <<pdo->prepare( $sql ); $stmt->execute( $params ); if ( $stmt->rowCount() == 1 ) return true; else return false; } } [/php]

Ok, thank you both very much. will have a proper gawp in the morning as it’s late and some of that went a bit over my head :o

Sponsor our Newsletter | Privacy Policy | Terms of Service