PHP: 2 includes, but only the first one works?

I made some simple php scripts and run into a problem with the include functions and mySQL connections.


If I execute test.php, it executes nav.php but crashes on nav1.php, when this tries to connect to the database.

If I change the order of the includes in test.php, nav1 gets executed easily, but nav.php crashes when connecting to the database.

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'www-data'@'localhost' (using password: NO) in /var/www/vhosts/ on line 42
Could not connect: Access denied for user 'www-data'@'localhost' (using password: NO)

As mentioned: If I change the order of the includes, it works fine, so both scripts and settings are ok.
Any idea what can cause this issue?

Who is Participating?
(So just put those variables at the top of nav and it should work).  If the variables are coming from an include file as well, then you can include that config file at the top of BOTH nav and nav2 but use include_once.

You should be deliberate about whether you mean to use include or include_once when you bring in a file.  Config files should be include_once.  Files that DO stuff (like display a nav) should usually be brought in with include.
Aamir SaeedCommented:
it might be due to include_once, try using include()
I don't think that include_once versus include would make a difference, even if you were including the same file (which you're not).

I think the problem is that nav1.php sets some variables and then connects to the database.  The other file, nav.php just tries to connect to the database.

If you include them in one order (nav1 and then nav),  then the variables ($userid and $password probably) are set and they are reused when nav is included.

If you include them in the other order (nav and then nav 1 which is what you are trying to do), the variables aren't set yet when nav tries to connect to the database.
SmoerbleAuthor Commented:
Thank you, that worked perfectly.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.