Home > Back-end >  Getting post data using Slim Framework for PHP
Getting post data using Slim Framework for PHP

Time:10-08

Currently working on CRUD methods using Slim Framework for PHP and testing it out with Postman. I've been able to select all or select a single object via Get methods and have tried to insert an object now and this is where my problem began. I've been following a YT video (https://www.youtube.com/watch?v=FYQrMr7oDv0 24:48) just to understand everything, however, the youtuber uses $request->getParam('paramName') which is not a method that is available to me. I've tried using $request->getParsedBody() and $request->getBody(), however all of these return nothing.

Below is the method in question

$app->post('/users/add', function (Request $request, Response $response, array $args) {
    $data = $request->getParsedBody();
    $username = $data['username'];
    $passhash = $data['passhash'];
    $email = $data['email'];

    $sql = "INSERT INTO user (username, passhash, email) VALUE (:username, :passhash, :email)";

    try {
        $db = new DB();
        $conn = $db->connect();

        $stmt = $conn->prepare($sql);

        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':passhash', $passhash);
        $stmt->bindParam(':email', $email);

        $result = $stmt->execute();

        $db = null;
        $response->getBody()->write(json_encode($result));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);
    } catch (PDOException $e) {
        $error = array (
            "message" => $e->getMessage()
        );

        $response->getBody()->write(json_encode($error));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(500);
    }
});

How am I supposed to get the data, which I'm trying to post with using Postman, link to Postman image below https://i.stack.imgur.com/4foNu.png

CodePudding user response:

Figured it out eventually, needed to add:

$app->addBodyParsingMiddleware();

After the app is created, in order to be able to Parse JSON, form data and XML, adding this middleware is necessary

  • Related