-1

I have 3 files in my project. For arguments sake let's called them a.php, b.php and c.php.

In a.php I have a declared variable: $sql_connection

In b.php I have declared a function: check_if_logged_in()

With these declared, I now want to be able to use the variables across my files. I have included a.php in my b.php file, and I included my b.php inside c.php.

I'd expect this all to work but for some reason b.php isn't getting $sql_connection from a.php?

My a.php file:

<?php

    $sql_connection = mysqli_connect("localhost", "user", "password", "database");

?>

My b.php file:

<?php

    include ("a.php");

    function check_if_logged_in() {

        $sqlquery = mysqli_query($sql_connection, ...

    }

?>

My c.php file:

<?php

    include ("b.php");

    check_if_logged_in();

?>
A Friend
  • 1,118
  • 10
  • 20
  • 1
    Your files "communicate" properly but you have to learn about [variable scope](http://php.net/manual/en/language.variables.scope.php). And **no**, the `global` keyword is not the solution to your problems. It is the cause of other, bigger problems that lurk in the dark, waiting for you to use it. – axiac Nov 07 '17 at 15:59
  • and @axiac interesting article! thank you :) – A Friend Nov 07 '17 at 16:02
  • 1
    @axiac I mean by defintion it is an article...if found the answer within the article you provided so thank you for that. – A Friend Nov 07 '17 at 16:10

2 Answers2

2

The problem is you are trying to use the variable $sql_connection within a function, which is initialised/declared outside; i.e. you have a scope issue!

Read up on it here: http://php.net/manual/en/language.variables.scope.php

Solution;

A. Pass $sql_connection to the function call like this: check_if_logged_in($sql_connection)

or

B. Use the global for e.g.

function check_if_logged_in() {
    global $sql_connection;
    $sqlquery = mysqli_query($sql_connection, ...
}

P.S. Although option B works; it is not recommended as it is considered bad pratise; see Are global variables in PHP considered bad practice? If so, why?

Latheesan
  • 19,790
  • 25
  • 89
  • 173
0

You need to pass the params.

function check_if_logged_in($sql_connection) {
$sqlquery = mysqli_query($sql_connection, ...

So

check_if_logged_in($sql_connection);
marcozipsp
  • 49
  • 3