我正在Slim 3应用程序中编写自己的类。我想有一个自己的课来处理数据库查询。代码如下:
var jsonStr = @"{
""User"":{
""username"":""Vinayaka"",
""email"":""Vinayaka@mindsol.in"",
""ref_id"":""43523543"",
""state_code"":""UP"",
""active_status"":""1"",
""user_type"":""Admin"",
""last_active"":""2018-09-22 13:50:23""
}
}";
var json = new JavaScriptSerializer();
var data = json.Deserialize<dynamic>(jsonStr);
foreach(KeyValuePair<string,object> p in data["User"])
{
Console.WriteLine(string.Format("{0} : {1}", p.Key, p.Value));
}
在routes.php中,我得到了这样的内容:
<?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'];
}
}
?>
但是访问路线会给我这个错误:
由于以下错误,应用程序无法运行:
在null上调用成员函数prepare()
文件:/var/www/vhosts/hosting114426.a2f69.netcup.net/httpdocs/rememberly/classes/DatabaseOperator.php行:25
跟踪<#0 /var/www/vhosts/hosting114426.a2f69.netcup.net/httpdocs/rememberly/src/routes.php(209):DatabaseOperator-> getUserID('testuser')
因此$ dbconnection为null似乎存在问题。但是,如果我在我的routes.php中使用$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);
,它将正常工作。因此$ this-> db不为空。
那这里是什么问题?
答案 0 :(得分:0)
<?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);
}
});