This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
like my title says, whenever I try to use my variables from another php file, it doesn't work (Undefined variable).
I did declare them in the file that I'm including.
For example, I have this file called variables.php that have this in it:
<?php
$DEBUG = TRUE;
$mysqli = new mysqli("127.0.0.1", "root", "", "29185917-database");
$DEBUG_LOG_FILE = "../log";
?>
And then I have another file called debug.php that tries to use the variable 'DEBUG' but it cannot access it. Here is my debug.php file:
<?php
require_once 'variables.php';
function echo_debug(string $message)
{
if($DEBUG) {
echo $message;
}
}
?>
Whenever I try to use my function echo_debug I get the error message :
Undefined variable 'DEBUG'.
Any help on this problem is appreciated :).
Functions have their own scope. The variable is accessible, just not from inside the function.
You could pass $DEBUG as a parameter
function echo_debug(string $message, bool $DEBUG)
Then you would call it as
echo_debug("comment that will help me debug in dev mode", $DEBUG);
Another option is to declare DEBUG as a constant,
define('DEBUG', true);
$mysqli = new mysqli("127.0.0.1", "root", "", "29185917-database");
$DEBUG_LOG_FILE = "../log";
Then, in your function you would check for that constant:
function echo_debug(string $message) {
if(DEBUG) { ... }
}
You could also use the global keyword, right above your if(), try to add global $DEBUG;.
require_once 'variables.php';
function echo_debug(string $message)
{
global $DEBUG;
if($DEBUG) { ... }
}
But generally the other two solutions are better, global variables are sometimes frowned upon.
As per my comment, you can also use a constant and avoid the variable issue altogether.
<?php
define('DEBUG', true);
$mysqli = new mysqli("127.0.0.1", "root", "", "29185917-database");
$DEBUG_LOG_FILE = "../log";
?>
Then in the function check if the constant has been defined
<?php
require_once 'variables.php';
function echo_debug(string $message) {
if (defined('DEBUG') && DEBUG === true) {
echo $message;
}
}
?>
do like this:
function echo_debug(string $message,$data)
{
if($data === TRUE) {
echo $message;
}
}
call function:
require_once 'variables.php';
$message = "comment that will help me debug in dev mode";
$output = echo_debug($message,$DEBUG);
print_r($output);
Related
I am having an issue with an include file accessing another include file (my db connection)
I have a site with the following layout ::
root/conn.php :: db connection file
root/site/file1.php :: regular page
root/site/include/func.inc :: file with functions in it
Each file is listed below with appropriate code...
conn.php ::
<?php
$host = 'localhost';
$db = 'mydb';
$user = 'myuser';
$pass = 'mypass';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli($host, $user, $pass, $db);
$conn->set_charset($charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
unset($host, $db, $user, $pass, $charset);
?>
file1.php ::
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
{ code that calls functions in func.php }
func.inc ::
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
{ various functions }
When I browse to /file1.php, I get the following error ::
PHP Notice: Undefined variable: conn in C:\inetpub\root\site\include\func.inc on line 231
PHP Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\inetpub\root\site\include\func.inc:231
my func.inc file cannot seem to find the conn.php file. I have also tried removing the include function from func.inc. There are other files in the /include folder that can access the conn.php file with the same include function.
The issue relates to something called the variable scope (https://www.php.net/manual/en/language.variables.scope.php)
==> Please read that to get detailed information
The second example describes your problem
func.inc
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
// to illustrate the issue, the include can be simplified to
// $conn = "something"; // => global scope variable
function myFunc(){
echo $conn; //no output - $conn exists ONLY in the local scope --> not available inside thisfunction
}
Solution 1:
func.inc
<?php
function myFunc($conn){
echo $conn; //outputs $conn
}
file1.php
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
//call function and pass the $conn, it's available here in the global scope
myFunc($conn);
Solution 2
but keep in mind global is considered as bad practice
func.inc
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
function myFunc(){
global $conn; //$conn is declared global in the local scope of this function
echo $conn; //outputs $conn from conn.php if you call myFunc from anywhere
}
I'm trying to include a variable from a different file into my main php file but I keep getting Undefined variable.
accounts.php
# GUEST CREDENTIALS
$host = 'localhost';
$guestAccount = 'oncofinder';
$guestPassword = 'xxxxxx';
$database = 'oncofinder';
#LOGGER CREDENTIALS
$loggerAccount = 'logger';
$loggerPassword = 'xxxxx';
connections.php
function guestConnection() {
try {
require 'accounts.php';
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
} catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
I tried to put my require in and out of my function but nothing works. I really thought this was straightfoward but I can't find an obvious solution.
Is there any thing I'm doing wrong? Isn't this the procedure?
Regards
I think you have variables defined in global scope but you try to use it in local scope.
To confirm naming scope issue try to:
require 'accounts.php';
function guestConnection() {
global $host, $database, $guestAccount, $guestPassword;
try {
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
...
This should work if your guestConnection() is in global scope not under any namespace or class.
or do move require out of try to get errors if any (file does not exist?):
function guestConnection() {
require('accounts.php');
try {
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
...
I had a similar problem on my CentOS server. Try using the full absolute path (server conf might not be configured to allow calling of same-level files this way):
require_once $_SERVER['DOCUMENT_ROOT']. '/path/to/accounts.php';
Note:
you can use require and it should still work. I just think require_once is safer (in terms of not accidentally duping code).
Help me with this code: I get this error.
Notice: Undefined variable: dbCon in C:\xampp\htdocs\Project\core\functions\general.php on line 5
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\Project\core\functions\general.php on line 5
Notice: Undefined variable: dbCon in C:\xampp\htdocs\Project\core\functions\Users.php on line 5
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\Project\core\functions\Users.php on line 5
Fatal error: Uncaught Error: Call to undefined function mysqli_result() in C:\xampp\htdocs\Project\core\functions\Users.php:8 Stack trace: #0 C:\xampp\htdocs\Project\login.php(4): user_exists(NULL) #1 {main} thrown in C:\xampp\htdocs\Project\core\functions\Users.php on line 8
Main folder(name -> PHP) has Index.php:
<?php
include 'core/init.php';
include 'includes/overall/header.php';
?>
PHP folder has Login.php:
<?php
include 'core/init.php';
if(user_exists('sudin') === true)
{
echo 'exists';
}
?>
under php/core folder init.php:
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
?>
under php/core/database connect.php:
<?php
$dbCon=mysqli_connect('localhost','root','','project_point');
?>
under php/core/functions Users.php:
<?php
function user_exists($username)
{
$username = sanitize($username);
$query = mysqli_query($dbCon,"SELECT COUNT('Login_ID')FROM 'login' WHERE 'Username' = '$username'");
return(mysqli_result($query,0)==1) ? true : false;
}
?>
under php/core/functions general.php:
<?php
function sanitize($data)
{
return mysqli_real_escape_string($dbCon,$data);
}
?>[enter image description here][1]
Sorry for the messy way, here is the treeview:
Thankful for the help
There are a few things wrong here.
Firstly, you have a variable scope issue and you're also using the wrong identifier qualifiers in your query being regular quotes:
So, remove the quotes for this:
SELECT COUNT('Login_ID')FROM 'login' WHERE 'Username'
^ ^ ^ ^ ^ ^ Remove those
or use ticks:
SELECT COUNT(`Login_ID`) FROM `login` WHERE `Username`
Checking for errors on it using mysqli_error($dbCon) http://php.net/manual/en/mysqli.error.php would have thrown you something about it once it would have fired.
Make your connection global in your user_exists() function
global $dbCon;
Read up on both:
Identifier qualifiers http://dev.mysql.com/doc/en/identifier-qualifiers.html
Variable scope http://php.net/manual/en/language.variables.scope.php
The connection variable is not defined in the function scope. The hotfix is to add it with the "global" construct.
function user_exists($username)
{
global $dbCon;
...
you are trying to use a local variable $dbCon inside the function user_exists.
you can just change that variable to be global
ex:
under php/core/database connect.php:
<?php
global $dbCon;
$dbCon=mysqli_connect('localhost','root','','project_point');
?>
under php/core/functions Users.php:
<?php
function user_exists($username)
{
global $dbCon;
$username = sanitize($username);
$query = mysqli_query($dbCon,"SELECT COUNT('Login_ID')FROM 'login' WHERE 'Username' = '$username'");
return(mysqli_result($query,0)==1) ? true : false;
}
?>
The issue is that $dbCon is not defined in the scope of any function.
You could do 3 things:
function user_exists($username){
$query = mysqli_query($GLOBALS['dbCon'] ...
function user_exists($username){
global $dbCon;
$query = mysqli_query($dbCon ...
However, using globals in functions like this is usually a bad coding style.
I would recommend doing something like the following:
function getconn(){
static $conn;
if(!isset($conn)){
$conn = new mysqli_connect(...);
}
return $conn;
}
function user_exists($username){
$query = mysqli_query(getconn() ...
I was just about to add the issues with your SQL syntax, but Fred beat me to it. I think you want backticks ` instead, not '.
Can someone help me understand this? It seams like I have done this a 100 times already, but for some reason I can't get it to work now.
I have a MySQL class where I do my SQL stuff.
I have a file called ajax.php which I do some AJAX requests to. In this file I have:
$mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
$show =$mysql->count('temp_vipalm', "21");
var_dump($show);
This returns the correct value as I expected. Now I want to use this in a function, so I can make it a little more dynamic, so in the same ajax.php file I create this function:
function menu($barid,$type)
{
//echo $barid; // returns correct value
//echo $bartype; //returns correct value
$mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
//usually $barid and $type goes in here, but I hardcoded the values for testing.
$show =$mysql->count('temp_vipalm', "21");
var_dump($show);
}
Now when running menu('21', 'temp_vipalm'); it returns NULL.
No matter what I do, it keeps returning NULL when inside the function - can anyone help me understand what's going on?
Your $server, $dbuser, $dbpass, and $dbselect variables are global. Within the function scope, you'll have to declare that those variables are coming from the global scope. Try this:
function menu($barid, $type) {
{
global $server, $dbuser, $dbpass, $dbselect;
$mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
// ...
}
Note: It would be a better idea to make these constants instead of variables. It's usually best to avoid variables in the global scope. If you accidentally overwrite one of those values somewhere else in your code, this function will use the wrong values.
There's two things to be aware of:
global variables must be declared global inside a function
the variable must already have been initialised
so this works fine:
<?php
$fred=42;
function printFred(){
global $fred; // declare it global
echo "fred is: ". $fred . "\n";
}
printFred();
?>
whereas this does not do what you might expect:
<?php
echo "Starting program...\n";
printStuff();
echo "the end";
exit();
$jim="Hello I'm jim";
function printStuff(){
global $jim;
echo $jim . "\n";
}
?>
because, in this case, the statement "$jim="Hello I'm jim";" is never executed.
Yours,
TonyWilk
The variables $server, $dbuser, $dbpass, $dbselect are not declared in the scope of the function, you should declare them as global assuming they're defined in the global env.
Below is my class. Fig A
<?php
class qcon{
public static $conn;
function dbcon()
{
if (!$conn)
{
$host = 'x';
$username = 'x';
$password = 'x';
$dbname = 'x';
$conn = mysqli_connect($host , $username , $password ,$dbname);
}
return $conn;
}
}
?>
Which is called here. Fig B
require_once(class file above);
function openSesame()
{
$boogey = new qcon();
$conn = $boogey->dbcon();
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Is causing
Notice: Undefined variable: conn in C:\...\xxxx\figAclass.php on line 10
I know I can simply turn errors off, but this seems unwise. I took a look at a generic SO question about the undefined variable notice. Obviously the advice was general - use isset. Had a go at isset and this does not seem correct for what I am trying to do.
Based on the code in figure A and B, is there anything obvious causing the notice to be flagged up. Could you demonstrate a fix that is in line with the existing code shown.
Don't use if (!$conn), which will check to see if the variable is true/false or contains a value, not if it's defined. Use this instead:
if(empty($conn))
This checks to see if the variable is defined, and if it is NULL/empty.
You also want to use $this->conn inside of your class instead, since you're defining it as a variable of the class.
Like I said in my comment above, since you have a static $conn, you need to refer to it like:
public function dbconn()
{
if (!self::$conn) {
// blah
}
return self::$conn;
}
Your error is happening because you're attempting to reference a variable named $conn, but due to scope, no such thing exists.
when you access it, you should use $this->conn, in example:
if(!$this->conn){...}
edited read the question too fast, sorry
You can't use if (!$conn)for this because that will only return 'true' or 'false'.
Use:
if empty($conn) instead.