Access db connections from functions in included files

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
bianster
Forum Newbie
Posts: 13
Joined: Sun Feb 08, 2004 3:47 am

Access db connections from functions in included files

Post 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;
?>
bianster
Forum Newbie
Posts: 13
Joined: Sun Feb 08, 2004 3:47 am

Post 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...
User avatar
DuFF
Forum Contributor
Posts: 495
Joined: Tue Jun 24, 2003 7:49 pm
Location: USA

Post 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.
bianster
Forum Newbie
Posts: 13
Joined: Sun Feb 08, 2004 3:47 am

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