Page 1 of 1

Function variables - Been 2 years since i touched php

Posted: Wed Mar 28, 2007 7:54 pm
by pinehead18
OK the $db variables are coming from config.inc.php
They echo before the fucntion, but not when i call the function.

So when i do db_connect(); on index.php it tries to connect but does not have the username etc.

Code: Select all

<?PHP

include('config.inc.php');


echo $db_username;
	echo $db_password;
	echo $db_host;
	echo $db_name;

// Functions page

//Connect to sql database

Function db_connect() { 
	
	$connection = mysql_connect($db_host, $db_username, $db_password) or die("Username/Password unable to connect to Mysql Datbase CHeck password/username/localhost");

	$db = mysql_select_db($db_name, $connection) or die("unable to connect to database");

	echo $db_username;
	echo $db_password;
	echo $db_host;
	echo $db_name;

	}

?>
Suggestions?

Thank you

Posted: Wed Mar 28, 2007 10:08 pm
by RobertGonzalez
Either pass them to the function as parameters or globalize them. I'd suggest passing them as globalizing is bad juju.

Posted: Thu Mar 29, 2007 2:05 am
by Dave2000
Is there anything specifically bad with having global variables?

Posted: Thu Mar 29, 2007 3:53 am
by stereofrog
Globals are considered "bad style". As long as you don't care about "style", they are ok. ;)

Alternatively to globalizing or passing params, you can also move the include into the function:

Code: Select all

function db_connect() { 
   include('config.inc.php');
   ....

Posted: Thu Mar 29, 2007 10:46 am
by RobertGonzalez
Realistically, if this is not a distributed application, you don't need to read the paramters into variables at all. Just plug them into the function.