Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
function buildGraphQLQuery($operationName, $fields, $pagination = [])
{
$query = $operationName;
// Add variables for filtering, pagination, etc.
if (!empty($pagination)) {
$query .= '(';
$query .= implode(', ', array_map(function ($key, $value) {
// Ensure proper GraphQL variable formatting (e.g., strings in quotes)
$formattedValue = is_numeric($value) ? $value : '"' . $value . '"';
return "$key: $formattedValue";
}, array_keys($pagination), $pagination));
$query .= ')';
}
// Add the fields to fetch
$query .= ' {';
$query .= implode("\n", $fields);
$query .= '}';
return '{' . $query . '}';
}
// Example Usage
$operationName = "users";
$fields = ['id', 'name', 'email'];
$variables = ['status' => 'ACTIVE'];
$pagination = ['first' => 10, 'after' => 'cursor123'];
$query = buildGraphQLQuery($operationName, $fields, $variables, $pagination);
echo $query;