1

I have a connect.php file which is supposed to verify the successful connection to my database. I then have a db.php file in which I've imported the connect.php file using the require('connect.php'); function in PHP. My IDE however still gives me an error saying that the $conn variable (as defined in the code below) is not defined. At first I thought that the import of connect.php into the db.php file may have somehow failed but this seems to not be the case since launching db.php file in the browser returns "Database connection success" which should not be possible unless the connect.php file has been correctly imported.

This is the content of the connect.php file :

<?php

$host = 'localhost';
$usr = 'root';
$passwd = '';
$db_name = 'testdb';

$conn = new MySQLi($host, $usr, $passwd, $db_name);

if($conn->connect_error){
    die('Database connection failure: ' . $conn->connect_error);
} else{
    echo "Database connection success.";
}

I then try to import this code into the db.php as seen below :

<?php

require('connect.php');

$sql = "SELECT * FROM users";
$stmt = $conn->prepare($sql);

However in db.php the $conn variable is undefined for some reason. Why is it undefined despite the import of it's definition being successful?

5
  • What error message are you getting that makes you think it's undefined? Commented Oct 21, 2021 at 19:12
  • Ignore the IDE as long as it works correctly. You may need to adjust your IDE's settings to automatically recognize the contents of your required file. Commented Oct 21, 2021 at 19:17
  • Hello. My IDE PhpStorm gives me an error saying that it is undefined to be precise "Undefined variable '$conn'" and as a possible fix it wants me to initialize the value first which I obviously don't want to do since it's already defined in the connect.php file. Commented Oct 21, 2021 at 19:17
  • @541daw35d thanks for accepting my answer but - even if it supplies some details and might be somewhat useful - it's wrong (or "not sufficiently right" :-) ). The correct answer was posted as a comment to your own answer, so you should un-accept mine and accept yours (or better, LazyOne's if/when they'll post one), so I can safely delete my own. Commented Oct 21, 2021 at 21:26
  • @541daw35d ...that said, it remains true that you should avoid global variables whenever possible :-) Commented Oct 21, 2021 at 21:27

2 Answers 2

2

This happens to me in PHPStorm if I incorrectly define the project root (even if this shouldn't be your case) or the include path.

Basically, the IDE can't "see" inside the connect.php and therefore acts as if the variables defined there don't exist. Note: as per @LazyOne's comment, this is a behaviour that you can change, requesting PHPStorm to look everywhere (at some performance cost, as you might imagine).

You could try defining a class to handle connections. This is a dirty hack:

<?php
    class MyConnection
    {
        private static $conn = null;

        public static instance() {
            if (null === static::$conn) {
                $host = 'localhost';
                $usr = 'root';
                $passwd = '';
                $db_name = 'testdb';
                static::$conn = new MySQLi($host, $usr, $passwd, $db_name);
                if(static::$conn->connect_error) {
                    die('Database connection failure: ' . static::$conn->connect_error);
                }
            }
            return static::$conn;
        }
    }

and then in the db.php,

require('connect.php');

$sql = "SELECT * FROM users";
$stmt = MyConnection::instance()->prepare($sql);

The difference being that I noticed some IDEs (PHPStorm and Microsoft VSCode) sometimes seem to handle classes way better than global symbols.

One of the advantages of this approach is that, in larger projects, if you define an autoloader, you can avoid most require and include altogether, and only load files on demand.

In this case, it's just an ugly hack that perhaps keeps the IDE happy. If you can fix things by e.g. informing the IDE about your project files and/or include paths, by all means you should do that.

I would avoid the tricks of declaring

global $conn;

because you might not notice when you use a variable that's globally undefined, or worse silencing the warnings with special comments because that makes you miss all undefined symbols.

/** @noinspection PHPUndefinedSymbol */

If nothing else avails, surrender and define a dummy variable:

/* dummy connection */
$conn = null;

require 'connect.php';

...
Sign up to request clarification or add additional context in comments.

2 Comments

Regarding the original code/FYI: that PhpStorm inspection by default checks for variables in a current file only (it does not take any include/require into an account: sometimes the variable may be included in 2..3 level deep include). That inspection has an option "Search for variable's definition outside the current file" for such scenarios (disabled by default for Performance and "write cleaner code" purposes).
@LazyOne I think I remember seeing that option - and keeping it off, as I usually don't need it. But thinking about it, this you wrote is actually the true answer to the OP's question, so you should maybe post it as such.
0

The error seems to be some sort of an error related to my IDE. If you encounter similar issues you may ignore this error or change the IDE highlighting properties to reflect such code style. If you are trying to use the variable inside of a function try to make the variable global using global $conn; (in my case). Putting the variable inside of the function and changing it's scope to global seems to have removed the error from the IDE completely.

1 Comment

Just configure that inspection to look for such variable in other (include) files and not this file only (which is by default). That inspection has an option "Search for variable's definition outside the current file" just for that.

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.