Hi There folks.

I was thinking of trying to make a php function in my sites configuration file so that I could keep all mysql database info in one central file.

I should mention that this is the first time I have tried to make my own function.

I have the file started, but can't get it to work like I'd hoped.

Is it possible to set a variable like

$username = "";

in a function and be able to insert that into a file.

I'd assumed that I would call the function and it would set the variable, but so far it hasn't worked.

Here is what I have

function &configDB($db)
{
 if($db=='calendar')
 {
$cfg[host]	= "localhost";
$cfg[user]	= "MyDBs";
$cfg[pass]	= "Pass";
$cfg[database]	= "MyDB1";
 }else
{
  $server	= "localhost";
  $dbusername	= "MyDBs";
  $dbpassword	= "Pass";
  $db_name	= "MyDB2";
 }
}

Then Call it by

configDB('main');

Would this be correct.

Help in passing variables would be appreciated.

Member Avatar for diafol

Your function variables are LOCAL variables (only visible to the function). You usually have to RETURN a value from the function to pass the value to the outside. Create your complete connection variable in the function and then do:

return $connection;

at the end of the function. Your example does nothing useful.

$db = 'whatever';
$conn = configDB($db);

This will then give you a your connection object in $conn and can be used to run queries:

$result = mysql_query('SELECT * FROM myTable',$conn);

However, you're hard-coding connection data (user + password). This is not recommended, although OK for testing.

Member Avatar for diafol

Damn! Forgot to code tag the examples. Sorry!

Damn! Forgot to code tag the examples. Sorry!

Not a problem, I caught your gist...

Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.