1

We are following the get started tutorial on github, all went well but we are stranded on the DB connection.

We have created the $db object:

    $db=new DB\SQL(
    'mysql:host=localhost;port=3306;dbname=liselore',
    'jow',
    ''
);

And we have set up a controller:

$f3->route('GET /',
function($f3) {

    $f3->set('result',$db->exec('SELECT achternaam FROM test1'));

    $template = new Template;
    echo $template->render('views/homepage.html');

    }
);

$f3->run();

However, we get this error:

Internal Server Error

Fatal error: Call to a member function exec() on a non-object

• fatfree-master/index.php:32 

I think the error relates to the $db object that is not set. However, we do have php-pdo set, i just checked via phpinfo().

Any help would be great, thx...

Liz
  • 189
  • 3
  • 10
  • try adding `global $db;` after this line `function($f3) {` - you have a scope issue – Latheesan Nov 12 '13 at 10:44
  • Thx for your answer, but all variables set using the $f3->set method are global, see: https://github.com/bcosca/fatfree#framework-variables – Liz Nov 12 '13 at 10:49
  • We are using the exact same code as the examples on the tutorial: https://github.com/bcosca/fatfree#databases – Liz Nov 12 '13 at 10:50
  • You're using a closure, you need to use `function($f3) use ($db) {` – naththedeveloper Nov 12 '13 at 10:53
  • Strange, if i move the new db/sql object creation to 'inside the function' then it all works... any thoughts on that? – Liz Nov 12 '13 at 10:55
  • @Liselore you need to read up on [variable scope](http://php.net/manual/en/language.variables.scope.php). – naththedeveloper Nov 12 '13 at 10:57

2 Answers2

3

You're using a closure which means the $db variable is no longer in scope. You need to use the use keyword to tell PHP to allow the use of the variable from the parent scope.

$f3->route('GET /', function($f3) use ($db) {
    $f3->set('result', $db->exec('SELECT achternaam FROM test1'));

    $template = new Template;
    echo $template->render('views/homepage.html');
});

$f3->run();
Community
  • 1
  • 1
naththedeveloper
  • 4,503
  • 6
  • 36
  • 44
1

You said it already:

all variables set using the $f3->set method are global

and yes, it's a common practise to save such objects in those framework vars. So just try

$f3->set('DB', $db=new DB\SQL('mysql:host=localhost;port=3306;dbname=liselore','jow',''));

and use this everywhere else:

$f3->set('result',$f3->get('DB')->exec('SELECT achternaam FROM test1'));
ikkez
  • 2,052
  • 11
  • 20