如何在 Slim API 中从我的 sql 内部注入数据


How to inject data from the reques tinside my sql in Slim API

我有一个Slim API,我需要创建一个函数来验证用户名/密码。我正在使用 POST,我想在 sql 的凭据中注入用户名。如果我使用 GET,我知道该怎么做,但我使用的是 POST。我该怎么做:

function authenticate($req, $resp, $args) {
    $credentials = json_decode($req->getBody());
    $sql = "SELECT * FROM ict_users WHERE usr_username = 'Insert the username here'";
    try {
        $db = DB_Connection();
        $stmt = $db->query($sql);  
        $password = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
    //check if the two password fits (use the password var)
    //create a session_key
    //Store the session_key in the DB
    //return the session_key
}

我在 AngularJS 服务中调用此函数:

$http.post(appConfig.apiURL + '/authenticate', credentials)
function authenticate($req, $resp, $args) {
    $credentials = json_decode($req->getBody());
    $sql = "SELECT * FROM ict_users WHERE usr_username = ?";
    try {
        $db = DB_Connection();
        $stmt = $db->prepare($sql);  
        $stmt->execute([$credentials['username']);
        $password = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
    //check if the two password fits (use the password var)
    //create a session_key
    //Store the session_key in the DB
    //return the session_key
}

像这样的东西。

我想通了:

function authenticate($req, $resp, $args) {
    $credentials = json_decode($req->getBody());
    $sql = "SELECT usr_password FROM ict_users WHERE usr_username='".$credentials->username."'";
    try {
        $db = DB_Connection();
        $stmt = $db->query($sql);  
        $password = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        if(empty($password)){
            echo '{"error":"login_failed"}';
        }
        else {
            if (password_verify($credentials->password, $password[0]->usr_password)) {
                echo '{"error":"login_success"}';
            }
            else {
                echo '{"error":"login_failed"}';
            }
        }
    }
    catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}