mysql_fetch_array() expects parameter 1 to be resource, boolean given
When you encounter the error mysql_fetch_array() expects parameter 1 to be resource, boolean given, the issue isn't with the fetch function itself; it's with how your query was executed. The underlying cause is almost always a fatal flaw in the application code: the use of the deprecated mysql_* extension combined with unsafe query construction.
The error message explicitly states that the first argument passed to mysql_fetch_array() is a boolean rather than a resource. In PHP, mysql_query() returns a resource (a link identifier) on success and false on failure. When your code attempts to iterate over a variable that holds false, the fetch functions immediately throw this specific error because they cannot operate on non-existent connections or result sets.
The Dual Failure Point in Your Code
Analyzing the provided snippet reveals two distinct, critical issues occurring simultaneously. First, you are using the mysql_* extension. This API has been deprecated since PHP 5.5 and removed entirely in PHP 7.0. Modern PHP environments will not run this code without warnings or fatal errors depending on the configuration.
Second, and more immediately relevant to the error message, is the query string construction:
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
Because variables are interpolated directly into the SQL string without delimiters, this code relies on client-side input validation or server-side magic quotes (which are no longer enabled by default). If the $username contains a single quote character ('), the resulting SQL becomes malformed. The database engine cannot parse the statement, causing mysql_query() to return false.
Consequently, when your while loop executes, it calls mysql_fetch_array(false), triggering the "boolean given" error. Even if the input doesn't contain a quote, this approach is fundamentally insecure due to SQL injection vulnerabilities.
Switching to mysqli or PDO
To resolve the immediate error and ensure long-term compatibility, you must migrate to either the mysqli extension or PDO. These modern interfaces separate query execution from result fetching and provide robust mechanisms for handling prepared statements.
Here is how you refactor the logic using mysqli. Notice that we first execute the query and check if it was successful before attempting to fetch rows. We also use a placeholder (?) for the user input, which forces the database driver to treat the value as data rather than executable code.
$host = 'localhost';
$db = 'your_database_name';
$user = 'username';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
// Prepare the statement to prevent SQL injection
$stmt = $pdo->prepare('SELECT FirstName FROM Users WHERE UserName LIKE :username');
$stmt->execute([':username' => '%' . $_POST['username'] . '%']);
// Iterate only if results exist
while ($row = $stmt->fetch()) {
echo htmlspecialchars($row['FirstName']);
}
} catch (\PDOException $e) {
// Handle errors gracefully without exposing internals to the user
error_log($e->getMessage());
echo "An error occurred.";
}
Handling False Results Explicitly
If you must work with older codebases where a full migration isn't immediately feasible, understanding how to check for false returns is essential. The mysql_query() function behaves differently than modern alternatives; it does not throw exceptions on failure by default. You must explicitly check the return value:
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE "' . addslashes($_POST['username']) . '"');
// Check if the query failed before trying to fetch
if (!$result) {
die('Query failed: ' . mysql_error());
}
while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
However, relying on mysql_* functions is strongly discouraged. The migration path to PDO or mysqli involves using prepared statements, which handle the binding of parameters safely and ensure that the result set returned by the query execution method is always a valid resource when the operation succeeds. This separation of concernsâvalidating the query execution before iterating resultsâis the standard pattern for preventing runtime type errors in database interactions.
