include connection function

Hey there everyone, I’m having issues with an include file for database connections. I’ve got a function in an include file that connects to a mySql db. It works fine with a file in the same directory, but not in a different directory. Seems like a scope issue, as it is able to find the include file in both cases, but I haven’t been able to figure it out yet :).

Thanks in advance

/login/incDB.php
[php]

<? function getConn() { global $conn; //connect to mysql $host = 'localhost'; $dbUsername = 'username'; $dbPassword = 'password'; $db = 'db'; $port = 3306; $conn = new mysqli($host, $dbUsername, $dbPassword, $db); if($conn->connect_errno > 0) { die('Unable to connect to database [' . $conn->connect_error . ']'); } } ?>

[/php]

/login/index.php
[php]
include_once ‘incDB.php’;

getConn();

    $sql = "call getLoginInfo ('$username','$password');";

    if(!$result = $conn->query($sql)){
    die('There was an error running the query [' . $conn->error . ']');
} else {
         echo 'logged in fine';
    }

[/php]

/upload/index.php
[php]

<? require_once ('../login/incDB.php'); //include_once ('../login/incDB.php'); function insertInfoToDB($year, $month, $day, $userUID) { //global $conn; getConn(); $sql = "call insertInfo ('$year', '$month', '$day', '$userUID');"; mysqli_query($conn, $sql); mysqli_close($conn); } ?>

[/php]

//error for mysqli_query($conn, $sql);
Notice: Undefined variable: conn in…
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in…

//error for mysqli_close($conn);
Notice: Undefined variable: conn in…
Warning: mysqli_close() expects parameter 1 to be mysqli, null given in…

Your connection function getConn() does not need to be in a function. Just include that page and you will have your connection.

I’m also guessing you are confusing include or require, all the they do is make up that particular page (example: index.php).

For instance:

[php]require(‘lib/includes/utilities.inc.php’);

…code…

  <nav <?php echo ($user && $user->isAdmin()) ? 'class="span5"' : 'class="span4"'; ?>>
    <ul>
      <li><a href="index.php">Home</a></li>
      <li><a href="order.php">Order</a></li>
      <li><a href="contact.php">Contact</a></li>
      <li><?php echo ($user && $user->isAdmin()) ? '<a href="logout.php">Logout</a>' : NULL; ?></li>
    </ul>
  </nav>[/php]

Obviously this isn’t working php code, but to show that $user will not work unless the require statement is there. It adds the code to the top of the page, it saves time and effort for you don’t have to type the same code over and over and over for every php page you have.

One last thing get rid of global, for that is bad practice.

Thanks for the help guys :).
Was able to get it working by putting the values into a class.

Sponsor our Newsletter | Privacy Policy | Terms of Service