Snippet vs. Include

Hello everyone,
I have a very basic question, as I’m very new working with Kirby. Here an example:

mysnippet.php contains database connections for multiple MySql-Databases I use e.g.:

$type     = option('MyDB.type');
$server    = option('');
$dbName    = option('MyDB.database');
$user      = option('MyDB.user');
$psw       = option('MyDB.password');
$port     = option('MyDB.port');  

  $conn = new PDO("mysql:host=$server; dbname=$dbName", $user, $psw);
}catch(PDOException $e){
    echo $e->getMessage();

snippet ('mysnippet');
Error thrown with message “Call to a member function query() on null” at this row in the template.


$result = $conn->query($sql,[$bind]);

include ('site/snippets/mysnippet.php');
Using include works fine.

What exactly is the difference between snippet and include?

Thanks a lot, in advance
Best Regards

snippet() is a function that echos or returns (with third parameter set to true) the HTML from the given snippet file. It therefore doesn’t expose any variables contained in it to where it is used.

On a side note, Kirby has a database class that provides an easy way to connect to databases.

1 Like