Running PHP v5.0.4 (and I'm a newbie to php)

I am setting up functions for the database and the only bit of code in the file that works is the bit that is commented out! I've tried the variables with "var " in front to declare them explicitly, I've taken the var out again. I've moved the variables to another file (which is where I want them to be in an ideal world) and tried with and without but get the same error there.

I thought anything declared at the top of the file like that would automatically be global but added them as parameters for the function just in case and still get errors. The errors are:

With explicit declaration:

Parse error: syntax error, unexpected T_VAR in [correct but v long path!] on line 8

Without I get four of these notices that I'm using the variables undeclared:

Notice: Undefined variable: dbhost in [long path] on line 16

then:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'ODBC'@'localhost' (using password: NO) in [long path] on line 16
Error connecting to mysql

Please help.

var $dbhost = 'HOSTNAME';
var $dbuser = 'USERNAME';
var $dbpass = 'PASSWORD';
var $dbname = 'DBNAME';

function db_open()
{
	global $db_conn;
	$db_conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
	mysql_select_db($dbname);
	//$db_conn = mysql_connect("HOSTNAME", "USERNAME", "PASSWORD") or die ('Error connecting to mysql');
	//mysql_select_db("DBNAME");
}

If I swap the comments around the function works just fine so I hope someone can see what's going wrong when I pass the db values in as parameters.

Thankyou!

The variables used inside a function have scope local to the function. To reference variables defined outside the function you will need to reference them in the global scope inside the function. So this should work for you:

$dbhost = 'HOSTNAME'; 
$dbuser = 'USERNAME'; 
$dbpass = 'PASSWORD'; 
$dbname = 'DBNAME'; 

function db_open() 
{ 
	global $db_conn, $dbhost, $dbuser, $dbpass, $dbname; 
	$db_conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); 
	mysql_select_db($dbname); 
}

Thankyou - that works!

I thought I had understood that part of the php docs but I guess not :-/

This article has been dead for over six months. Start a new discussion instead.