dongliling6336 2017-02-17 15:55
浏览 51

Slim Framework - 如何在正常函数中查询db

I'm very new to PHP and Slim Framework which helps creating APIs. Everything is ok If i query db inside $app->post or get. But I want to separate it to normal function. It will help when I need to use it later in other APIs.

I tried to call this

$app->get('/search/[{phone}]', function($request, $response, $args) use ($app){
    $token = $response->getHeader('token');
    // $phone = $args['phone'];
    if (isTokenValid($token)){
        return $this->response->withJson("valid");
    }
    return $this->response->withJson("invalid");

});

My isTokenValid() function

function isTokenValid($token){
    $sql = 'SELECT id FROM users WHERE token = :token';
    $s = $app->db->prepare($sql); //<< this line 25
    $s->bindParam(':token', $token);
    if ($s->execute()){
        if($sth->rowCount() > 0){
            return true;
        }
    }
    return false;
}

But I get 500 Internal Server Error

Type: Error
Message: Call to a member function prepare() on null
File: /Applications/MAMP/htdocs/aigoido/src/functions.php
Line: 25

How to call it outside $app? Thanks.

  • 写回答

2条回答 默认 最新

  • dongmanzui8486 2017-02-17 16:14
    关注

    Pass $app to your function as parameter. The function has it own context so $app is not available without that.

    function isTokenValid($token, $app){
        $sql = 'SELECT id FROM users WHERE token = :token';
        $s = $app->db->prepare($sql); //<< this line 25
        $s->bindParam(':token', $token);
        if ($s->execute()){
            if($sth->rowCount() > 0){
                return true;
            }
        }
        return false;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?