0

Im trying to get data from my database and echo it with a variable, but I have a problem with that. When I try to get my variables from different files it shows me this error:

Undefined variable: con in.

Here some codes:

Code from functions.php:

include "authentication.php";

function GetData() {
$id = session_id();
$result3 = mysqli_query($con,"SELECT * FROM accounts where id='$id'");
while($row3 = mysqli_fetch_array($result3));
{ 
$email=$row3['email'];
$fullname=$row3['fullname'];
$usualname=$row3['usualname'];
$lastname=$row3['lastname'];
}
}

Code from authentication.php:

$DATABASE_HOST = 'localhost';
$DATABASE_USER = '***';
$DATABASE_PASS = '***';
$DATABASE_NAME = '***';

$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {

    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}

This also happens when I try to get variables from other files.. Here you get some screenshots of the error from different files and different variables:

enter image description here

enter image description here

Both files are in the same directory called PHPscripts:

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
Murat
  • 101
  • 2
  • 8
  • Where is the location of `authentication.php`? Is that file included properly? – Talk2Nit Aug 03 '19 at 13:52
  • @Talk2Nit It's in the same folder as function.php – Murat Aug 03 '19 at 13:57
  • Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Progman Aug 03 '19 at 18:36

2 Answers2

1

This looks like a problem of scoping.

Remember that in PHP, variables in the global scope cannot be accessed from a function. You must explicitly do something like global $con; inside the function GetData() before you try to access $con.

From a system design point of view this isn't the best approach. It will make it hard to keep track of your variables. You won't know who (which part of your script) is accessing that global and you won't know how it is being modified or in what order. This can lead to some bugs that are very difficult to identify.

Oloff Biermann
  • 706
  • 5
  • 18
0
require_once dirname(__FILE__) . auth.php;

Require_once or require with Unix full path works like a charm. Replace include stroke in your code.

Vladimir
  • 441
  • 1
  • 4
  • 14