0

I have db.php with the following code.

<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "password";
$dbName = "test";
$databaseLink = new mysqli ($dbHost, $dbUser, $dbPass);
if($databaseLink)
{
    mysqli_select_db($databaseLink,$dbName);
}
?>

which I usually import on to other php page like this

<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/core/include/db.php";
?>

and works fine. I can start querying using $databaseLink. But there is one page where its not working. But if I explicitly define the connection like this $databaseLink= mysqli_connect("localhost", "root", "password", "test"); it works. There are other php files in the same directory which has no issues.

I have tried

<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/core/include/db.php";
global($databaseLink);
?>

But that does not seem to work too. I have looked it up online for examples but can find any help.

5
  • 2
    You need to require $path; (or better yet require_once ) Commented Jan 26, 2018 at 7:01
  • Are you sure the path is still the same and correct every time you use it? Plus, why not use require_once $pathtodb instead? Commented Jan 26, 2018 at 7:02
  • include_once($path);or require_once($path) Commented Jan 26, 2018 at 7:03
  • 2
    Using the global keyword is bad practice though Commented Jan 26, 2018 at 7:07
  • @Akintunde007 it's also not necessary here Commented Jan 26, 2018 at 8:41

2 Answers 2

1

you forget to require your db.php file

require_once($path);
Sign up to request clarification or add additional context in comments.

2 Comments

OP's method of initializing the database connection is perfectly valid
Thanks this Works. But cant I do without that.
0

You can simply use include at the top of your php code to link in another php page.

include '/core/include/db.php';

Comments

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.