I have problem with PDO im my project. Error: Call to a member function query() on null

Error: Call to a member function query() on null.
Here my code
Part of index.php:

$app = new Slim\App();
$container = $app->getContainer();

$container['db'] = function ($c) {
    $pdo = new PDO('mysql:host=localhost;dbname=fileSiteDb', 'test', 'test');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};
$container['MainController'] = function($c) {
    $view = $c->get("view");
    $db = $c->get("db");
    return new App\Сontrollers\MainController($view, $db);
};

$app->get('/download/{file}', 'MainController:getIndex');
$app->run();

Part of MainController:

class MainController {
    protected $view;
    protected $db;

    public function __construct(\Slim\Views\PhpRenderer $view, PDO $db) {
        $this->view = $view;
        $this->db = $db;
    }

    function getIndex($request, $response, $args) {
        global $db;
        if($db->query("SELECT count(*) FROM files WHERE `file_server_name` = '".$file."'")->fetchColumn() != 0) { // Error in this row
            $file_name = $db->query("SELECT `file_name` FROM files WHERE `file_server_name` = '$file'")->fetchColumn();
            $file_size = round(filesize("files/$file") / 1000 / 100) / 10;
        } else {
            header('location: 404');
        }
     }
 }
  1. Just use the member variable (and never use global variables).
if ($this->db->query(...)
  1. Better use the $response object to return a http redirect.
return $response->withStatus(302)->withHeader('Location', 'the-url');
  1. For the PDO::ERRMODE_EXCEPTION to work, it should be added to the flags instead.

return new PDO($dsn, $username, $password, $flags);

1 Like

Thank you very much!