pdo - PHP: Why functions can not avail the variables of a required file? -


this code made return name of chosen $id database,

#db informations (username/password) require('/path/to/db_informations.php');   # function return 'name of $id db function getname($id){    $link = new pdo($dsn, $user, $pwd);     $query = "select `name` `tables` `id`=$id";     $smt = $link->prepare($query);    $smt->execute();    $name = $smt->fetch(pdo::fetch_assoc);     return $name['name']; }  # db_informations contain credentials connect database. ($dsn, $user, $pwd) 

mmh require(/path/to/db_informations.php') not working inside function if put `require();' function in body. not understand mistake, can please explain me:

why /path/to/file not included php? , how to?

this variable scope issue.

$dsn, $user, $pwd global variables , not defined within getname() function scope.

the quickest way resolve use global.

function getname($id) {    global $dsn, $user, $pwd;    // code... } 

however, not recommend using global (they evil). better thing define database object (pdo) @ global scope , pass around functions/classes. called dependency injection.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -