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
N开发者_JS百科otice: 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.
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
}
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.
精彩评论