1

I have simple php script but from some reason when i call getUserRoles function from another script i get "Undefined variable: mysqli" as you can see i included dbConnect script. (Path is 1000% correct)

<?php

require_once '../dbConnect.php';


function getUserRoles() {
    $stmt = $mysqli->prepare("SELECT ur.roleName from user_role as ur where ur.userId = ?");

    $stmt->bind_param("i", $_SESSION["id"]);
    $stmt->execute();

    $stmt->bind_result($roleName);

    $roles = array();

    $stmt->bind_result($roleName);

    while ( $stmt->fetch() ) {
        $roles[] = $roleName;
    }

    return $roles;
}
?>

And from this script i want to call getUserRoles(), but when i call function i get "Undefined variable: mysqli" and i have no idea why, can anyone tell me where i'm making mistake ?

<?php
require_once '../dbConnect.php';
require_once '../security/securityService.php';

getUserRoles();

?>

In that script i include securityService.php script where i have getUserRoles() and i successfully make function call, but inside that function i cant connect to database.

Sahbaz
  • 1,242
  • 4
  • 17
  • 39

1 Answers1

1

That's because mysqli is not globalized. Add:

global $mysqli;

under:

function getUserRoles() {

To global the mysqli var into the function.

aperpen
  • 718
  • 7
  • 10
  • It is working, but i just read that is super bad practice, can you tell me better solution for this one ? – Sahbaz Jan 28 '17 at 20:34
  • I don't think that global a db conection it's a bad practice... But if you want you can also use: `$GLOBALS['mysqli']` to access to your mysqli var inside a function – aperpen Jan 28 '17 at 23:53