I have a config folder which contains the db.php file, which contains the following code:
<?php $host = 'localhost'; $dbname = 'test'; $charset = 'utf8'; $dbuser = 'root'; $dbpassword = ''; $opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); $dsn = "mysql:host = $host; dbname = $dbname; charset = $charset"; $pdo = new PDO($dsn, $dbuser, $dbpassword, $opt); Then I have a folder with models: models which contains the file WorkersModel.php with the following code:
<?php function getAllWorkers() { $stmt = $pdo->query('SELECT * FROM `workers`'); while($row = $stmt->fetch()) { echo $row['name']; } } The problem is that I cannot access the $ pdo variable from this function, or rather, I can, but only if I declare $ pdo global inside the function:
<?php function getAllWorkers() { global $pdo; ... This model connects the controller from the controllers folder and calls the functions of the model in its functions.
All these folders: models , config , controllers are on the same level. At the same level is the www folder, which in turn is index.php , which "calls" the controllers, connects files from the config folder and contains the following code:
<?php require_once '../config/config.php'; require_once '../libs/Functions.php'; require_once '../config/db.php'; $controllerName = isset($_GET['controller']) ? ucfirst($_GET['controller']) : 'Index'; $actionName = isset($_GET['action']) ? $_GET['action'] : 'index'; loadPage($twig, $controllerName, $actionName); In the Functions.php file, I have all sorts of common functions, such as page loading and template loading.
So: how do I properly initialize the PDO and connect it to the model?