Decoding PDO Access Denied Errors in PHP Scripts
You are encountering a PDOException because your script is attempting to establish a database connection without providing authentication credentials, even though you believe you have configured them correctly. The error message explicitly states: Access denied for user 'nobody'@'localhost' (using password: NO). This indicates that the PDO constructor received an empty username and password, defaulting to the anonymous nobody user, which lacks permission to access your database.
Looking closely at the stack trace, the failure occurs inside the testdb_connect() function on line 34 during the instantiation of the new PDO object. The core issue lies in how the variables are being passed into that function versus how they are defined outside of it.
Variable Scope and Function Arguments
In your provided code snippet, the variables $hostname, $username, and $password are defined at the top level of the script. However, inside the testdb_connect() function, you are passing these variables as arguments to the PDO constructor.
function testdb_connect(){
$dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password);
// ...
}
While PHP allows functions to access variables defined in the global scope if they are not explicitly declared as parameters, relying on this behavior is a source of frequent bugs. More critically, your error output shows using password: NO. This confirms that the values passed to the second and third arguments of the PDO constructor were effectively empty strings or null at the moment of execution.
If you intended to pass the global variables directly without listing them in the function signature, PHP will look for them in the global scope. However, a common pitfall occurs when these variables are modified later or if they are inadvertently redefined within a different context (such as inside an include file like header.php). In your stack trace, the error originates in /home/a/public_html/d/inc/header.php. If that file contains its own definitions for $username or $password that differ from the ones you see in your article script, the function will use those incorrect values.
Fixing the Connection Logic
To resolve this, ensure that the credentials are explicitly passed as arguments to the function and that no conflicting definitions exist in included files. Here is a corrected structure where the function accepts the connection details as parameters:
<?php
function testdb_connect($hostname, $username, $password, $dbname) {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname;charset=utf8mb4", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
} catch (PDOException $e) {
// In production, log this to a file rather than echoing directly
error_log($e->getMessage());
die('Database connection failed. Please check credentials.');
}
}
// Define credentials
$hostname = 'localhost';
$username = 'removed'; // Replace with actual user
$password = 'removed'; // Replace with actual password
$dbname = 'removed'; // Replace with actual database name
$dbh = testdb_connect($hostname, $username, $password, $dbname);
echo 'Connected to database';
?>
By explicitly passing the variables, you eliminate ambiguity regarding scope. Additionally, adding PDO::ATTR_ERRMODE set to ERRMODE_EXCEPTION ensures that any SQL errors (like syntax issues in your query) are thrown as exceptions rather than resulting in silent failures or generic warnings.
Query Syntax and Security Considerations
Beyond the connection error, there are significant issues with the query logic following the connection attempt. Your SQL statement uses single quotes around identifiers instead of keywords:
$sql = "SELECT * FROM 'radiologyArticles' WHERE 'id' = :id";
In MySQL, table names and column names must be enclosed in backticks () or left unquoted if they do not contain reserved words. Single quotes denote string literals. If a database exists named radiologyArticlesbut the query treats it as a string literal'radiologyArticles', the parser will fail because it expects a table name, not a string value. Furthermore, querying for an ID inside single quotes will look for a row where the column literally contains the text "id"`, rather than the numeric value of the ID.
The corrected query should be:
$sql = "SELECT * FROM `radiologyArticles` WHERE `id` = :id";
Finally, note that you are fetching all rows (SELECT *) but only iterating through them to display content. This is generally acceptable for small datasets but can become a performance bottleneck with large tables. If you need to ensure the script handles cases where no articles exist, always check if $row is false before accessing articleTitle or articleBody, or use PDO::FETCH_NULL and add null checks in your PHP loop.
For more robust database management patterns within larger applications, consider how frameworks like Laravel handle connection pooling and environment-specific configuration via the .env file, which prevents hardcoding credentials directly into source code.