试图获取非对象的属性“名称”,但我有数据名称

时间:2020-12-31 02:59:43

标签: php mongodb xampp postman

<块引用>

我通过邮递员做 REST API MONGODB-PHP CRUD 并尝试获取 非对象的属性“名称”。但我有一个数据名称。为什么 发生?我使用 XAMPP 3.2.2 PHP 7.2.1 是否有任何修复建议 它吗?

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")
    );
}
?>

我如何修复错误

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

1 个答案:

答案 0 :(得分:1)

您的 json_decode 传递的 seccond 参数为 true,这意味着 $data 是数组, 它不是一个对象 任何一个 改变

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

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

或使用 $data 作为数组 $data["name"]

<块引用>

关联 当为 true 时,JSON 对象将作为关联数组返回;当为 false 时,JSON 对象将作为对象返回。当为 null 时,JSON 对象将作为关联数组或对象返回,具体取决于是否在标志中设置了 JSON_OBJECT_AS_ARRAY。

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