Page 1 of 1

Access db connections from functions in included files

Posted: Sun Feb 15, 2004 7:51 am
by bianster
Hi all,

I have a file named connectDB.inc.php:

Code: Select all

<?php
define("DB_SERVER", "localhost");
define("DB_USER", "");
define("DB_PASSWORD", "");
define("DSN", "records");
//Establish database connection
$DB_CONN = odbc_connect(DSN, DB_SERVER, DB_USER, DB_PASSWORD) or die ("Could not connect to server...");
?>
the file in included in the global scope (as in NOT within any function) but when I try to use $DB_CONN to perform some DB queries in functions that are declared in ANOTHER included file (databaseFunctions.inc.php), I run into plenty of problems

when I try to run the query on $DB_CONN, I receive "unexpected T_GLOBAL" errors.

How am I supposed to use $DB_CONN here??

Code: Select all

<?php
require "connectDB.inc.php";	
require 'databaseFunctions.inc.php';

function authenticate($emailAddr, $password)&#123;
	$salt = substr($password, 0, 2);
	$encryptedPassword = crypt($password, $salt);
	$query = "SELECT name FROM member WHERE email = '$emailAddr' AND password = '$encryptedPassword'";
	
	$rs = executeQuery(global $DB_CONN, $query);

databaseFunctions.inc.php:

Code: Select all

//a sample function in the file
<?php
function executeQuery($DB_CONN, $query)&#123;
	$queryRs = odbc_exec($DB_CONN, $query) or die ("Unable to execute query for the MEMBER table...");
	return $queryRs;
&#125;
?>

Posted: Sun Feb 15, 2004 8:08 am
by bianster
Ah...dumb me...

Minutes after posting this...I found the solution in this very forum.
Just declare the connection variable as global in the function...

global DB_CONN;


I just have another question...for functions like odbc_fetch_row(), is the database connection needed to perfom it successfully? If it is, how do I actually make it available to the function, yep, its in an included file also...

apologies for any stupidity displayed by me...

Posted: Sun Feb 15, 2004 9:32 am
by DuFF
I don't know much about ODBC, but I'm guessing it works in the same way MySQL does. You shouldn't need a database connection to go through the results because they are already stored in a variable from the query.

Posted: Mon Feb 16, 2004 5:58 am
by bianster
I made a mistake in the 2nd post, setting DB_CONN to global in the function actually DOES NOT work...

When I try to fetch a row from the result set, I get this "Invalid ODBC resource identifier" message...