Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

php - 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 MongoDBDriverBulkWrite();
$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:xampphtdocsmongodelete.php on line 22

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...