Сохранение возвращаемого значения из graphql в переменной php - PullRequest
1 голос
/ 12 марта 2020

Я делаю мутацию в graphql из php через cURL. Мой запрос GraphQl:

mutation MyMutation {
  insert_presentaciones(objects: {imagen: "logo.png", presentacion: "Ernesto", teatro_id: 3}) {
    returning {
      id
    }
  }
}

, как я могу сохранить это возвращаемое значение "id" в переменной в php. Весь мой код таков до сих пор:

<?php

$service_url = 'http://100.100.100.175:8080/v1/graphql';

$curl = curl_init($service_url);

$curl_post_data = array("query" => 'mutation MyMutation {insert_presentaciones(objects: {imagen: "logo.png", presentacion: "Ernest", teatro_id: 3}){returning {id}}}');
$data_string =  json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);

$curl_response = curl_exec($curl);

if ($curl_response === false) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('Hubo un error al ejecutar el cURL. Info Adicional: ' . var_export($info));
}
curl_close($curl);

echo $curl_response;

echo $info;

?>

Он правильно вставляет данные в базу данных, но когда он возвращает идентификатор, я не знаю, как его сохранить.

Возвращает:

{"data":{"insert_presentaciones":{"returning" : [{"id":167}]}}}

Я хочу сохранить эти 167. в переменную.

Любая помощь ?? Большое спасибо и извините за мой английский sh

1 Ответ

0 голосов
/ 13 марта 2020

объект json использует json_decode (php .net / manual / en / function. json -decode. php) код должен выглядеть так, сначала декодируйте, а затем вы можете получить идентификатор

$decoded= json_decode($curl_response, true);

и затем, чтобы извлечь из него данные, у вас есть несколько способов.

$id=null; // default value

if(isset($decoded['data']['insert_presentaciones']['returning'][0]['id'])){
   //check if the array element is set if yes asign value 
   $id=$decoded['data']['insert_presentaciones']['returning'][0]['id'];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...