Search code examples
phpmongodbxampppostman

Trying to get property 'name' of non-object but i have data name


I do REST API MONGODB-PHP CRUD via postman and got Trying to get property 'name' of non-object. but i have a data name. Why did it happen ? I use XAMPP 3.2.2 PHP 7.2.1 are there any suggestion to fix it ?

delete.php

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// include database file
include_once 'db.php';
$dbname = 'dbprakt';
$collection = 'classroom';

//DB connection
$db = new DbManager();
$conn = $db->getConnection();

//record to delete
$data = json_decode(file_get_contents('php://input'), true);

//_id field value
$name = $data->{"name"};

// delete record
$delete = new MongoDB\Driver\BulkWrite();
$delete->delete(
    ["name" => $name]
);
$result = $conn->executeBulkWrite("$dbname.$collection", $delete);

// verify
if ($result->getDeletedCount() == 1) {
    echo json_encode(
        array("message" => "Error while saving deleted")
    );
} else {
    echo json_encode(
            array("message" => "Error while deleting record")
    );
}
?>

how i fix error

Trying to get property 'name' of non-object in C:\xampp\htdocs\mongo\delete.php on line 22

Solution

  • your json_decode pass the seccond parameter is true which mean $data is array, it not an object either change

    json_decode(file_get_contents('php://input'), true)
    

    to

    json_decode(file_get_contents('php://input'))
    

    or using $data as array $data["name"]

    associative When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects. When null, JSON objects will be returned as associative arrays or objects depending on whether JSON_OBJECT_AS_ARRAY is set in the flags.

    https://www.php.net/manual/en/function.json-decode.php