Function variables - Been 2 years since i touched php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pinehead18
Forum Contributor
Posts: 329
Joined: Thu Jul 31, 2003 9:20 pm

Function variables - Been 2 years since i touched php

Post 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
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Either pass them to the function as parameters or globalize them. I'd suggest passing them as globalizing is bad juju.
Dave2000
Forum Contributor
Posts: 126
Joined: Wed Jun 21, 2006 1:48 pm

Post by Dave2000 »

Is there anything specifically bad with having global variables?
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post 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');
   ....
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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.
Post Reply