Question
I am trying to select data from a MySQL table in PHP, but I get an error like this:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
My code looks like this:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE $username");
while ($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
Why does this error happen, and how should I correctly query the database and fetch rows?
Short Answer
By the end of this page, you will understand why functions like mysql_fetch_array(), mysql_fetch_assoc(), and mysql_num_rows() fail when they receive false instead of a query result. You will learn how to detect query errors, fix SQL string issues, and use modern PHP database APIs such as mysqli or PDO with prepared statements.
Concept
The error means your fetch function expected a query result resource (or result object in newer APIs), but your query actually failed and returned false.
In old PHP mysql_* functions:
mysql_query()returns a resource when the SQL query succeeds.- It returns
falsewhen the SQL query fails. - Functions like
mysql_fetch_array()only work on a successful query result.
So this error is usually not the real problem. The real problem happened earlier, when mysql_query() failed.
In your example, this line is the likely cause:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE $username");
There are two important issues here:
- The PHP variable is placed directly into SQL without proper quoting.
- User input is being inserted into SQL unsafely, which creates an SQL injection risk.
For a string value, SQL usually needs quotes:
WHERE UserName = 'alice'
Mental Model
Think of mysql_query() like ordering a package.
- If the order succeeds, you get a box back.
- If the order fails, you get nothing useful, just a failure signal.
mysql_fetch_array()is like trying to open the box.
If there is no box because the order failed, trying to open it causes an error.
So the key idea is:
- Send the query
- Check whether it succeeded
- Only then fetch rows
Another way to think about it:
- Query function = make the request
- Fetch function = read the returned rows
- Error message = you tried to read rows from a failed request
Syntax and Examples
Old mysql_* style (for understanding the error)
This style is outdated, but it helps explain the problem:
$result = mysql_query("SELECT * FROM Users WHERE UserName = 'alice'");
if ($result === false) {
die(mysql_error());
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['FirstName'];
}
What this does:
- Runs the query
- Checks if it failed
- Only fetches rows if the query succeeded
Why your original query breaks
Broken example:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE $username");
Problems:
$usernameis not quoted as a stringLIKEis usually used with patterns such as%john%
Step by Step Execution
Consider this modern example:
$username = "alice";
$stmt = $mysqli->prepare("SELECT FirstName FROM Users WHERE UserName = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
Step by step:
-
"alice"is stored in$username. -
PHP prepares this SQL:
SELECT FirstName FROM Users WHERE UserName = ? -
bind_param("s", $username)tells MySQL:- there is one parameter
- it is a string (
s) - its value is
Real World Use Cases
This concept appears anywhere PHP code reads from a database.
Login and account lookup
Applications often query users by:
- username
- ID
If the query fails and the code fetches rows anyway, you get the same resource/result error.
Search features
When building search forms with LIKE, developers often:
- forget to add
%wildcards - forget to quote strings
- build SQL unsafely from user input
Admin dashboards
Dashboards fetch rows for:
- user lists
- orders
- reports
- inventory
A bad query can break the page unless the result is checked before fetching.
API endpoints
Backend APIs often query data and return JSON. A failed query should return a controlled error response instead of calling fetch methods on a failed result.
Data import scripts
Scripts that process CSV or external data may run many queries. Proper error checking helps you identify exactly which query failed.
Real Codebase Usage
In real projects, developers rarely call a query and immediately fetch rows without checks.
Common patterns
Guard clause after query execution
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception($mysqli->error);
}
This stops execution early if the query failed.
Prepared statements for all user input
$stmt = $mysqli->prepare("SELECT * FROM Users WHERE UserName = ?");
$stmt->bind_param("s", $username);
This is the standard safe pattern.
Validation before querying
if (empty($_POST['username'])) {
die('Username is required');
}
Validation prevents pointless or broken queries.
Common Mistakes
1. Not checking whether the query succeeded
Broken code:
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
If $result is false, the fetch call fails.
Better:
$result = mysql_query($sql);
if ($result === false) {
die(mysql_error());
}
2. Forgetting quotes around string values
Broken code:
$username = 'alice';
$sql = "SELECT * FROM Users WHERE UserName = $username";
This produces invalid SQL.
Correct idea:
$sql = "SELECT * FROM Users WHERE UserName = 'alice'";
Comparisons
| Concept | What it means | When to use |
|---|---|---|
| Query failure | SQL is invalid, connection issue, table/column problem | Check errors immediately |
| Zero rows returned | Query worked, but matched nothing | Handle as a normal case |
= | Exact match | Username, ID, email |
LIKE | Pattern match | Search boxes, partial text |
mysql_* | Old removed PHP API | Only useful for understanding legacy code |
mysqli | Modern procedural/OOP MySQL API | Good default for PHP + MySQL |
PDO |
Cheat Sheet
Quick rules
- A fetch function needs a successful query result.
- If the query fails, the result is usually
false. - Always check the query result before fetching.
- Prefer
mysqliorPDO, notmysql_*. - Use prepared statements for user input.
- Use
=for exact matches andLIKEfor patterns.
Old error pattern
$result = mysql_query($sql);
if ($result === false) {
die(mysql_error());
}
Safe mysqli pattern
$stmt = $mysqli->prepare("SELECT FirstName FROM Users WHERE UserName = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
= ->();
( = ->()) {
[];
}
FAQ
Why does mysql_fetch_array() say it expected a resource?
Because mysql_query() failed and returned false instead of a valid query result.
What does “boolean given” mean in this error?
It means the fetch function received false, which is a boolean value, not a database result.
How do I find the actual SQL error in old PHP code?
Check the return value of mysql_query() and print mysql_error() if it is false.
Should I use LIKE for usernames?
Usually no. For exact username matching, use =. Use LIKE only for partial matches.
Why is direct use of $_POST in SQL dangerous?
It can allow SQL injection, where a user changes the meaning of your SQL query.
What should I use instead of mysql_* functions?
Use mysqli or PDO with prepared statements.
Mini Project
Description
Build a simple user lookup form in PHP that searches for a user by username and displays the matching first name. This project demonstrates safe database querying, result checking, and row fetching using mysqli prepared statements.
Goal
Create a PHP script that accepts a username, queries the Users table safely, and prints the user's first name or a helpful message if no match is found.
Requirements
- Accept a username from a form submission using
POST. - Validate that the username is not empty.
- Query the
Userstable using a prepared statement. - Display the matching
FirstNamevalues. - Show a message when no users are found.
- Handle database errors safely.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.