-1

This is code is made to return the name of a chosen $ID from the database,

#DB Informations (username/password)
require('/path/to/db_informations.php');


# This function return the 'name of the $ID from the db
function getName($ID){
   $link = new PDO($dsn, $user, $pwd);

   $query = "SELECT `name` FROM `tables` WHERE `id`=$ID";

   $smt = $link->prepare($query);
   $smt->execute();
   $name = $smt->fetch(PDO::FETCH_ASSOC);

   return $name['name'];
}

# db_informations contain the credentials to connect the database. ($dsn, $user, $pwd)

Mmh require(/path/to/db_informations.php') is not working inside the function even if I put `require();' function in the body. I do not understand my mistake, can you please explain me:

Why the /path/to/file is not included by PHP? and How to?

torr
  • 1,256
  • 3
  • 11
  • 20

2 Answers2

1

Your DB variables are not in scope of your getName() function. You need, at bare minimum:

function getName(...) {
   global $dsn, $user, $pwd;
   ...
}

In the greater picture, you should NOT be using global variables, nor should you be creating a DB connection in every function call. Connect to the database ONCE in your db setup file, then simply re-use that connection for the rest of the DB operations in your script.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0

This is a variable scope issue.

$dsn, $user, $pwd are global variables and not defined within the getName() function scope.

The quickest way to resolve this is to use global.

function getName($ID) {
   global $dsn, $user, $pwd;
   // code...
}

However, I do not recommend using global (they are evil). The better thing to do would be to define your database object (PDO) at the global scope and pass it around to your functions/classes. This is called dependency injection.

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • But If I had to retain a database connection open what should I use instead of global variable? – torr Jul 23 '13 at 19:21
  • As I said, define your database object within the global scope, such from your *db_information* script. For start, you could simply move it outside the `getName()` function. – Jason McCreary Jul 23 '13 at 19:23