Jump to content

Better Practice?


astralaaron

Recommended Posts

Say you have a function, db_connection() and you have some other functions that query the database, for this example just queryDB();Which would be considered better practice?db_connection();queryDB();or inside of the queryDB function call the db_connection?queryDB(){db_connection();}

Link to comment
Share on other sites

Ideally you would have 1 database class which would include the connection as a property, instead of a series of functions. Your query method of the class can check to see if a connection was already made and make one if not, or you can pass the login credentials to the class constructor and connect at that time.

Link to comment
Share on other sites

I am using the mysqli version of what justsomeguy tells. The below example explains why this is a great tool:database.php

<?php//Database connection$db = array (  'host' => $db_host,  'user' => $db_user,  'pass' => $db_pass,  'dbname' => $db_name);//Create the connection as object$mysqli = new mysqli($db['host'], $db['user'], $db['pass'], $db['dbname']);if(mysqli_connect_errno()){  trigger_error('Fout bij verbinding: '.$mysqli->error);}?>

part of my main.php file that handles a part of the configuration

<?php//Database connection vars$db_host = 'xxxx';$db_user = 'xxxx';$db_pass = 'xxxx';$db_name = 'xxxx';//Include the database connectioninclude_once('database.php');//Select the defaultsettings from the configtablefunction configuration(){  $sql = "SELECT * FROM table_xxxxx WHERE xxxxID=xxx";  if(!$Config = $GLOBAL['mysqli']->query($sql))  {	trigger_error('Fout in query: '.$GLOBAL['mysqli']->error);  }  else  {	if($config = $Config->fetch_assoc())	{		  $theme = $config['DefaultTheme'];	  $language = $config['DefaultLanguage'];	}  }}?>

As you can see, the class takes care of the connection while I don't have to worry about any extra coding to include the connection to my functions. The way I explaned in my first example just uses pure functions and thats also a way to handle stuff and still keep things flexible. In your way (using a function in a function) it cannot be possible to add a new parameter to your db_connection(); like db_connection($par); without changing all the function calls in the rest of your files. Its just a way to keep things flexible and it will safe time in the long run when you have to update/change things.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...