I’m working on a backend project using PHP (v7.4) and MySQL for a GraphQL implementation. The project is part of an assignment, and I’m required to follow certain guidelines, such as using object-oriented principles (OOP) without frameworks and ensuring MySQLi integration. I’ve been stuck with an Internal Server Error when querying my GraphQL endpoint, and I’ve tried multiple fixes but haven’t been able to resolve it.
Every time I run a GraphQL query for fetching products and categories, I receive the following response:
{
"errors": [
{
"message": "Internal server error",
"locations": [
{
"line": 1,
"column": 3
}
],
"path": [
"categories"
]
},
{
"message": "Internal server error",
"locations": [
{
"line": 1,
"column": 26
}
],
"path": [
"products"
]
}
],
"data": {
"categories": null,
"products": null
}
}
I’ve checked the error logs, but there isn’t much useful information beyond generic internal server errors.
code context :
simplified product model :
namespace AppModel;
use AppDatabaseDBConnection;
abstract class Product {
private $db;
protected $id, $name, $inStock, $description, $category_id, $brand;
public function __construct($id, $name, $inStock, $description, $category_id, $brand) {
$dbConnection = new DBConnection();
$this->db = $dbConnection->getConnection();
}
public function save() {
$stmt = $this->db->prepare("INSERT INTO products (id, name, inStock, description, category_id, brand) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssisss", $this->id, $this->name, $this->inStock, $this->description, $this->category_id, $this->brand);
$stmt->execute();
$stmt->close();
}
public static function getAll() {
$dbConnection = new DBConnection();
$conn = $dbConnection->getConnection();
if (!$conn) {
error_log("Database connection is null in Product::getAll");
return null;
}
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result === false) {
error_log("Query failed in Product::getAll: " . $conn->error);
return null;
}
return $result->fetch_all(MYSQLI_ASSOC);
}
}
graphql and schema setup :
use GraphQLTypeDefinitionObjectType;
use GraphQLTypeDefinitionType;
use GraphQLTypeSchema;
use AppModelCategory;
use AppModelProduct;
class GraphQL {
static public function handle() {
$categoryType = new ObjectType([
'name' => 'Category',
'fields' => [
'id' => Type::int(),
'name' => Type::string(),
]
]);
$productType = new ObjectType([
'name' => 'Product',
'fields' => [
'id' => Type::string(),
'name' => Type::string(),
'inStock' => Type::int(),
'description' => Type::string(),
'category_id' => Type::int(),
'brand' => Type::string(),
]
]);
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'categories' => [
'type' => Type::listOf($categoryType),
'resolve' => function () {
$categories = Category::getAll();
if (!$categories) {
return null;
}
return $categories;
}
],
'products' => [
'type' => Type::listOf($productType),
'resolve' => function () {
$products = Product::getAll();
if (!$products) {
return null;
}
return $products;
}
]
]
]);
$schema = new Schema(['query' => $queryType]);
$input = json_decode(file_get_contents('php://input'), true);
$query = $input['query'];
$variableValues = $input['variables'] ?? null;
$result = GraphQLGraphQL::executeQuery($schema, $query, null, null, $variableValues);
$output = $result->toArray();
return json_encode($output);
}
}
DBConnection class :
namespace AppDatabase;
use mysqli;
class DBConnection {
private $connection;
public function __construct() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "shopbase";
$this->connection = new mysqli($servername, $username, $password, $dbname);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function getConnection() {
return $this->connection;
}
public function close() {
$this->connection->close();
}
}
Error handling queries :
'resolve' => function () {
try {
$products = Product::getAll();
if (!$products) {
throw new Exception("Products query returned null");
}
return $products;
} catch (Exception $e) {
error_log('Error in products resolve: ' . $e->getMessage());
return null;
}
}
What I’ve Tried:
1 – Checking Database Connections: I confirmed that the DBConnection class works, and I’m able to connect to the MySQL database without errors.
2- Querying Directly in MySQL: The queries (SELECT * FROM products) work perfectly in the MySQL terminal.
3-Adding Error Logging: I added error_log calls to log connection and query issues, but I still see “Internal Server Error” with no detailed log output.
4- Adjusted GraphQL Resolver Logic: Made sure that the resolve functions for categories and products catch exceptions, but it still throws the same error.
5-tried to use fastroute package with changes in the htaccess file and httpd file from apache (i am usign xampp) and it wasnt greate 🙂 at all
Question:
What could be causing these GraphQL internal server errors? Is there something wrong in the way I’m handling database connections in my GraphQL setup or in how I’m structuring the queries?
Any insights or suggestions would be greatly appreciated! Thanks in advance.
I really really crying for help at this moment , i have been at this problem for so long and the deadline is in 20 days i am freaking out i cant finish it so plz help
//update : thanks to the comments i opened every single error log and the last log i got from the internal server error thing is :[20-Sep-2024 17:21:52 Europe/Berlin] Variables: null
[20-Sep-2024 17:21:52 Europe/Berlin] Before executeQuery
[20-Sep-2024 17:21:52 Europe/Berlin] After executeQuery
[20-Sep-2024 17:21:52 Europe/Berlin] After executeQuery
[20-Sep-2024 17:21:54 Europe/Berlin] Starting handle function
[20-Sep-2024 17:21:54 Europe/Berlin] Query: "query {rn products {rn idrn namern inStockrn descriptionrn category_idrn brandrn }rn}rn"
[20-Sep-2024 17:21:54 Europe/Berlin] Variables: null
[20-Sep-2024 17:21:54 Europe/Berlin] Before executeQuery
[20-Sep-2024 17:21:54 Europe/Berlin] Fetching products from database
[20-Sep-2024 17:21:54 Europe/Berlin] After executeQuery
// that means the excuteQuery is working , i edited the graphql handle() method to log me the errors if the method itself dont work .
//here is updated graphql :
<?php
namespace AppController;
use GraphQLGraphQL as GraphQLBase;
use GraphQLTypeDefinitionObjectType;
use GraphQLTypeDefinitionType;
use GraphQLTypeSchema;
use GraphQLTypeSchemaConfig;
use AppModelCategory;
use AppModelProduct;
use AppModelOrder;
class GraphQL
{
static public function handle()
{
error_log('Starting handle function');
// Define Category Type
$categoryType = new ObjectType([
'name' => 'Category',
'fields' => [
'id' => Type::int(),
'name' => Type::string(),
],
]);
// Define Product Type
$productType = new ObjectType([
'name' => 'Product',
'fields' => [
'id' => Type::string(),
'name' => Type::string(),
'inStock' => Type::int(),
'description' => Type::string(),
'category_id' => Type::int(),
'brand' => Type::string(),
],
]);
// Define Order Type
$orderType = new ObjectType([
'name' => 'Order',
'fields' => [
'order_id' => Type::int(),
'product_id' => Type::string(),
'quantity' => Type::int(),
'created_at' => Type::string(),
'updated_at' => Type::string(),
],
]);
// Define Query Type
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'categories' => [
'type' => Type::listOf($categoryType),
'resolve' => function () {
try {
$categories = Category::getAll();
if ($categories === null) {
throw new Exception("Categories query returned null");
}
return $categories;
} catch (Exception $e) {
error_log('Error in categories resolve: ' . $e->getMessage());
return null;
}
},
],
'products' => [
'type' => Type::listOf($productType),
'resolve' => function () {
try {
error_log('Fetching products from database');
$products = Product::getAll();
if ($products === null) {
throw new Exception("Products query returned null");
}
error_log('Products fetched: ' . json_encode($products));
return $products;
} catch (Exception $e) {
error_log('Error in products resolve: ' . $e->getMessage());
return null;
}
},
], // <-- Add this closing bracket
'echo' => [
'type' => Type::string(),
'args' => [
'message' => Type::string()
],
'resolve' => function ($root, $args) {
return $args['message'];
}
],
],
]);
// Define Mutation Type
$mutationType = new ObjectType([
'name' => 'Mutation',
'fields' => [
'createOrder' => [
'type' => $orderType,
'args' => [
'product_id' => ['type' => Type::string()],
'quantity' => ['type' => Type::int()],
],
'resolve' => function ($rootValue, $args) {
try {
$order = new Order($args['product_id'], $args['quantity']);
$order->save();
return $order;
} catch (Exception $e) {
error_log('Error in createOrder mutation: ' . $e->getMessage());
return null;
}
},
],
],
]);
// Create the schema
$schema = new Schema(
(new SchemaConfig())
->setQuery($queryType)
->setMutation($mutationType)
);
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = $input['variables'] ?? null;
// Log the query and variables for debugging
error_log('Query: ' . json_encode($query));
error_log('Variables: ' . json_encode($variableValues));
// Before the executeQuery method
error_log('Before executeQuery');
try {
$result = GraphQLBase::executeQuery($schema, $query, null, null, $variableValues);
error_log('After executeQuery'); // Check if we get here
} catch (Exception $e) {
error_log('Error in executeQuery: ' . $e->getMessage());
}
$output = $result->toArray();
header('Content-Type: application/json; charset=UTF-8');
return json_encode($output);
}
}
//i checked before and after the excutequery() if its working or not and it does work so now i dunno what else is the problem
abdelrhman atef is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2