0

There are multiple times in one page where I need to connect and subsequently query a MySQL database, yet my code won't let me. I think it might be something to do with how my files are nested but it makes no sense. I am opening the SQL connection in the header file. The top of the offending page looks like the following:

<?php 
$page_title = 'Dashboard';
include('templates/header.inc'); // includes a 'require_once('mysqli_connect.php') and a small query to the database;
require_once('includes/functions.php');
require_once('includes/dashboard_sql.php'); // Contains functions which connect to database (which are failing.)
?>

I get the PHP error

Notice: Undefined variable: dbc in /Library/WebServer/Documents/pediatory_site/includes/dashboard_sql.php

Where $dbc is the database connection defined in mysqli_connect.php.

If anyone could help me out that would be great.

4
  • You should only connect to the DB once per request and reuse that connection. Commented May 18, 2010 at 22:31
  • That's the problem, the connection variable is getting lost somewhere? Commented May 18, 2010 at 22:33
  • Are you including mysqli_connect.php ? Commented May 18, 2010 at 22:34
  • Then you need the singleton pattern for your DB/Connection object. Commented May 18, 2010 at 22:34

2 Answers 2

1

It probably has to do with scope.

$dbc = 1;

function foo() {
   echo $dbc; // Undefined variable
   echo $GLOBALS['dbc']; // 1, like defined above
   $otherVar = 2;
}

echo $otherVar; // Undefined variable

If the $dbc variable is used multiple times, it's shorter to write:

function foo() {
   global $dbc;
   echo $dbc; // 1, like defined above
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think when using the Require_Once method for creating a db connection the var gets cleared after the method closes the connection to the file. Try require or include for this kind of operations, and check if that works

<?php 
$page_title = 'Dashboard';
include('templates/header.inc'); // includes a 'require_once('mysqli_connect.php') and a small query to the database;
require_once('includes/functions.php');
include('includes/dashboard_sql.php'); // Contains functions which connect to database (which are failing.)
?>

so, i changed the require_once into an include method in the code you posted, try and go to the templates/header.inc and change the require_once method to a include and check if that helps.

it should. otherwise try creating the connection to the database in the same file, instead seperetated connections over separate files.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.