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
pinehead18
Forum Contributor
Posts: 329 Joined: Thu Jul 31, 2003 9:20 pm
Post
by pinehead18 » Wed Mar 28, 2007 7:54 pm
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
RobertGonzalez
Site Administrator
Posts: 14293 Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA
Post
by RobertGonzalez » Wed Mar 28, 2007 10:08 pm
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 » Thu Mar 29, 2007 2:05 am
Is there anything specifically bad with having global variables?
stereofrog
Forum Contributor
Posts: 386 Joined: Mon Dec 04, 2006 6:10 am
Post
by stereofrog » Thu Mar 29, 2007 3:53 am
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');
....
RobertGonzalez
Site Administrator
Posts: 14293 Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA
Post
by RobertGonzalez » Thu Mar 29, 2007 10:46 am
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.