Domanda

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...

È stato utile?

Soluzione

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();

Altri suggerimenti

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'));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top