0

The connection file is:

$DBconnect = mysqli_connect("localhost", "root", "", "project" );

And this works on all pages except one, which is giving this error: Undefined variable: DBconnect

for this part:

include_once('connection.php');
// Function that will convert a user id into their username
function getusername($uid) {

$res = mysqli_query($DBconnect, "SELECT username FROM users WHERE id='".$uid."' LIMIT 1") or die(mysql_error());

Thanks for advice

zigg76
  • 55
  • 1
  • 7
  • 1
    You define the variable in the global scope, but try to access it in function scope. That does not work. Try this inside the function: `$_GLOBALS['DBconnect']` – arkascha Sep 23 '15 at 10:46
  • Read up about variable scope. But for a quick fix, include the line `global $DBconnect;` in the function. – Geoff Atkins Sep 23 '15 at 10:47
  • 1. Make sure that this is the correct path to connection.php. 2. It is defined in your global and not the needed(function) scope. – Konstantin Rachev Sep 23 '15 at 10:48
  • Ah yes thanks trying to use the global variable in the function was the problem – zigg76 Sep 23 '15 at 10:53

2 Answers2

0

Change this

    function getusername($uid){
$res = mysqli_query($DBconnect, "SELECT username FROM users WHERE id='".$uid."' LIMIT 1") or die(mysql_error());
}

to this

    function getusername($uid){
    global $DBconnect;
    $res = mysqli_query($DBconnect, "SELECT username FROM users WHERE id='".$uid."' LIMIT 1") or die(mysql_error());
    }

or

function getusername($uid,$DBconnect){
        $res = mysqli_query($DBconnect, "SELECT username FROM users WHERE id='".$uid."' LIMIT 1") or die(mysql_error());
        }
Payer Ahammed
  • 887
  • 1
  • 5
  • 16
0

This is a scope issue.

$DBConnect is available in the Global scope, but you cannot get access to the global scope in a function automatically. So pass the $DBConnect as a parameter to the function and all is well.

include_once('connection.php');

function getusername($uid, $DBConnect) {

    $res = mysqli_query($DBconnect, "SELECT username 
                                     FROM users 
                                     WHERE id='$uid' LIMIT 1"); 
    if ( ! $res ) {
       echo mysql_error();
       exit;
    }

}

// call function with an extra parameter i.e. the $DBConnect

getusername($uid, $DBConnect);
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149