Home > Enterprise >  How to create a dynamic GraphQL query using variables in PHP?
How to create a dynamic GraphQL query using variables in PHP?

Time:08-31

I have a graphQL query that looks like this:

$query = <<<'JSON'
query{
   mainProducts(where:{productType:{eq:2}}) {
       name, productID
   }
}
JSON;
$variables = '';

$json = json_encode(['query' => $query, 'variables' => $variables]);

$chObj = curl_init();
curl_setopt($chObj, CURLOPT_URL, ‘https://whateverurlitis.com’);
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);    
curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($chObj, CURLOPT_HEADER, true);
curl_setopt($chObj, CURLOPT_VERBOSE, true);
curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
curl_setopt($chObj, CURLOPT_HTTPHEADER,
     array(
            'Content-Type: application/json;charset=utf-8',
            'Authorization: bearer '.MYTOKEN 
        )
    ); 

$response = curl_exec($chObj);
echo $response;

My issue is, at the moment I need to replace the query parameter with a variable to make it dynamic, and the variable can be either a number or array of numbers and I would need to loop them.

Could someone please enlighten me on how to replace the number 2 for productType with a variable?

CodePudding user response:

First of all, there's no need to differentiate between either a number or array of numbers. If it's just one number, you could just pass an array with one number. This will make your schema simpler.

In order to add dynamic variables to the query, you'll need to redo your query to allow passing variables. The following should do the trick:

query MainProducts($productTypes: [Int!]!) {
   mainProducts(where:{productType:{eq:$productTypes}}) {
       name, productID
   }
}

This way, you'll be able to pass productTypes variable of type [Int!]!, which is an array of integers.

Now, all that's left is to pass product types IDs to the query as a variable:

$variables = [1,2,3];

You can read more about passing arguments to a query here.

  • Related