Warning: mysqli_query(): Couldn't fetch mysqli

Warning: mysqli_query(): Couldn't fetch mysqli

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Resource Leak Causing mysqli_query(): Couldn't fetch mysqli

The error message Warning: mysqli_query(): Couldn't fetch mysqli is one of those PHP warnings that immediately points to a specific, often overlooked resource management issue. It does not mean your database connection string is wrong or that the MySQL server has crashed. Instead, it indicates that the variable you are passing to mysqli_query() is no longer pointing to an active connection object.

In the code snippet provided, the root cause becomes apparent almost instantly upon inspection of the flow between the first and second queries. The script successfully executes the initial query:

$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");

However, the very next line is critical:

mysqli_close($conn);

By closing the connection immediately after fetching the top-level categories, you sever the link to the database server. When the script proceeds into the while loop to iterate through those categories, it attempts to run a second query inside the loop body:

$subcategories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'subcategory'");

At this precise moment, $conn is null because mysqli_close() was invoked earlier. PHP cannot execute a query without an open connection, resulting in the warning. The fact that the first query works while the second fails confirms that the issue is strictly temporal; the resource exists initially but is destroyed before it is needed again.

Resource Lifecycle and Scope

In PHP, database connections are resources that must be explicitly closed or allowed to time out. Closing a connection is generally good practice for preventing memory leaks in long-running scripts, but it requires strict adherence to scope. If you close a connection before every subsequent operation depends on it, your logic will break.

The provided solution involves moving the mysqli_close() call to the very end of the script, ensuring the connection remains open throughout the entire rendering process. Alternatively, if performance is a concern and you need to close connections between different logical sections of code, you must re-establish the connection before executing dependent queries. Given that this script renders a hierarchical list where subcategories depend on the current category, keeping a single persistent connection active for the duration of the page load is the standard and most efficient approach.

Optimizing Database Queries with Joins

Beyond fixing the immediate error, the SQL logic presented in the source material reveals an opportunity for optimization. The code fetches all top-level categories, then iterates through them to fetch all subcategories from the entire table each time. This results in a Cartesian product scenario where you are re-scanning the categories table for every single top-level item.

If your dataset grows beyond a few thousand rows, this approach will degrade performance significantly due to repeated full-table scans. A more robust solution involves restructuring the query logic. Instead of nested queries that scan the same table repeatedly, you can use a single JOIN operation or a grouped subquery to retrieve both levels in one efficient pass.

For instance, if your categories table has a parent_id column linking children to parents, a single query like this would be more performant:

SELECT c.category, c.type, parent.category as parent_name
FROM categories c
LEFT JOIN categories parent ON c.parent_id = parent.id
WHERE c.type IN ('category', 'subcategory')
ORDER BY parent.category, c.category;

This allows you to iterate through the result set once, handling the hierarchy in your PHP logic without needing multiple database round-trips. While fixing the connection leak is the immediate priority, refactoring the query strategy ensures scalability as your application grows.

If you are migrating away from procedural MySQLi to leverage modern PHP frameworks or need to manage connections more robustly within an MVC structure, platforms like Laravel provide built-in connection management that abstracts these lifecycle concerns. You can find further resources on handling database interactions in modern stacks at https://laravelcompany.com.

Our network