Saving returning value from graphql in php variable

Viewed 564

Iam making a mutation to graphql from php via cURL. My GraphQl query is:

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

how I can store this returning value "id" into a variable in php. My entire code is this until now:

<?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;

?>

It inserts correctly the data into the database but when it returns the Id I dont know how to store it.

It returns:

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

i want to store that 167 into a variable.

Any help?? thanks a lot and sorry for my english

1 Answers

its a json object use json_decode (php.net/manual/en/function.json-decode.php) the code should look like so first decode and then you can get the id

$decoded= json_decode($curl_response, true);

and then to get the data out of it you have a couple of ways.

$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'];
}
Related