I am writing my own classes in my Slim 3 Application. I'd like to have an own class to process Database Queries. Code looks like this:
<?php
class DatabaseOperator {
private $dbconnection;
function __construct($dbconnection) {
$this->dbconnection = $dbconnection;
}
public function getUserPermissions($user_id) {
$user_permissions = "SELECT list_id FROM permissions WHERE user_id='$user_id'";
$sth = $dbconnection->prepare($user_permissions);
$sth->execute();
$user_permissions_result = $sth->fetchAll();
$result_permissions = array();
foreach ($user_permissions_result as $row) {
$list_id = $row['list_id'];
$this->logger->info("User has access to List ID: " . $list_id);
array_push($result_permissions, $list_id);
}
return $result_permissions;
}
public function getUserID($username) {
$sqluser = "SELECT user_id FROM users WHERE username='$username'";
// TODO: Android REG_ID from DB
$sth = $dbconnection->prepare($sqluser);
$sth->execute();
$res = $sth->fetch(PDO::FETCH_ASSOC);
return $res['user_id'];
}
}
?>
In my routes.php I got something like this:
$app->get('/login', function (Request $request, Response $response, array $args) {
$username = $request->getServerParam('PHP_AUTH_USER');
if (isset($username)) {
$this->logger->info("Authenticated user: " . $username);
$databaseOperator = new DatabaseOperator($this->db);
$user_id = $databaseOperator->getUserID($username);
But accessing the route gives me this error:
The application could not run because of the following error:
Call to a member function prepare() on null
File: /var/www/vhosts/hosting114426.a2f69.netcup.net/httpdocs/rememberly/classes/DatabaseOperator.php Line: 25
Trace< #0 /var/www/vhosts/hosting114426.a2f69.netcup.net/httpdocs/rememberly/src/routes.php(209): DatabaseOperator->getUserID('testuser')
So there seems to be an issue with the $dbconnection being null. But if I use $this->db->prepare(QUERY)
in my routes.php it works without problems. So $this->db is not null.
So what is the problem here?
<?php
$slimSettings = [
/* ... */
];
$container = new \Slim\Container(['settings' => $slimSettings]);
$container['db'] = function ($c) {
$dns = ''; // PDO dns
$dbUser = ''; // database user
$dbPass = ''; // database password
return new \PDO($dns, $dbUser, $dbPass);
};
/* ... */
$app = new \Slim\App($container);
/* ... */
$app->get('/login', function (Request $request, Response $response, array $args) {
$username = $request->getServerParam('PHP_AUTH_USER');
if (isset($username)) {
$this->logger->info("Authenticated user: " . $username);
$databaseOperator = new DatabaseOperator($this->db);
$user_id = $databaseOperator->getUserID($username);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.