?
Solved

Help with PHP Variable Scope

Posted on 2015-02-21
4
Medium Priority
?
151 Views
Last Modified: 2015-02-22
I have a script that calls a function which runs a query and returns a result. The calling script includes an application file at the top via require_once. This application file includes my session, database connection, function, and other often needed scripts using the same method, via require_once.

I call the function from inside the script and get an error because it is not able to find my dbconnection variable (I am using mysqli). The only way I have been able to get the function to work is by including the dbconnection code inside the function.

How can I access that variable and not have to include the code a second time?

//top of calling file
<?php require_once '../includes/application.php'; ?>

//contents of application file
<?php require_once("../includes/sessions.php"); ?>
<?php require_once("../includes/dbconnect.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php require_once("../includes/breadcrumb.php"); ?>

//contents of dbconnect file
<?php
  // Create a database connection
  $dbhost = "";
  // $dbuser = "";
  // $dbpass = "";
  $dbuser = "";
  $dbpass = "";
  $dbname = "";
  $db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
  // Test if connection occurred.
  if(mysqli_connect_errno()) {
    die("Database connection failed: " . 
         mysqli_connect_error() . 
         " (" . mysqli_connect_errno() . ")"
    );
  }
?>

//function call from within the calling file
<?php
 $crewresult = getCrewDescription($li["CrewId"]);
 echo "Code: " .  $crewresult['CrewCode'] . "Description: " . $crewresult['CrewDescription']; 
?>

//finally the function itself
<?php
	function getCrewDescription($CrewID) {

		$querystring =  " SELECT yadda";
		$querystring .= " FROM yidda";
		$querystring .= " WHERE yackity = ";
		$querystring .= (int) schmackity;
		
		$result_get_crew = mysqli_query($thisdb, $querystring);

		if(!$result_get_crew) {
			die("Database error in function getCrewDescription.");
		}
		if(mysqli_num_rows($result_get_crew)) {
			while ($record = mysqli_fetch_assoc($result_get_crew)) {
				$aarray_crew = array("CrewCode" => $record['CrewCode'], "CrewDescription" => $record['LongDescription']);
			}
		} else {
				$aarray_crew = array("CrewCode" => 0, "CrewDescription" => "No Crew Found");
		}	
		mysqli_free_result($result_get_crew);
		return $aarray_crew;
	}
?>

Open in new window

0
Comment
Question by:medievalman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 83

Accepted Solution

by:
Dave Baldwin earned 2000 total points
ID: 40623690
You have to make the connection variable a 'global' in each routine or function that uses it.  Also... everything between the PHP close and open tags will be sent to the browser if this is for a web page including what you think are comments.  '//' only works for comments Inside the PHP tags.

I just edited the top section although I didn't see anything in your code that wouldn't work between a single open and close tag.  If you use anything that requires headers or cookies to be sent, those extra characters will cause it to fail.
<?php //top of calling file
require_once '../includes/application.php';

//contents of application file
require_once("../includes/sessions.php");
require_once("../includes/dbconnect.php");
php require_once("../includes/functions.php");
require_once("../includes/validation_functions.php");
require_once("../includes/breadcrumb.php"); ?>

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40623743
Without dragging this into a really long question and answer session, you may not get the best answer and the answer you need for application development.  So rather than trying to answer, I'll just leave this here as encouragement for your future learning.  It's not simple at first, but it transforms your software development process from one that can only survive in isolation to one that can be shared with your colleagues and proved to be testable, dependable and reliably error free.

Learn about Dependency Injection.  Using PHP require_once() gives you dependencies that are impossible to mock or test.  Same thing with the global keyword.  Injecting the dependencies (like the database connection and the function definitions) enables you to mock these dependencies, causing the mock objects to return predictable and testable values.

http://en.wikipedia.org/wiki/Dependency_injection
0
 

Author Comment

by:medievalman
ID: 40623766
Thank you, Dave. Declaring global $db in the function did the trick. The comments in the code section of my post were merely for guidance as to what code was where.
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 40623837
You're welcome, glad to help.
0

Featured Post

Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question