PHP and MySQL Select a Single Value

PHP and MySQL Select a Single Value

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

Stefan Bogdanescu

Founder & Senior Architect

PHP and MySQL Select a Single Value

The error message you are encountering—Catchable fatal error: Object of class stdClass could not be converted to string—isn't a mystery; it is a direct consequence of how mysql_fetch_object() works versus what your code expects. When you retrieve data using this function, PHP returns an object of the stdClass class containing all columns from the result set. Even though you only asked for one column, the returned variable $value remains an object wrapper around that single row. You cannot assign an entire object to a string-based session variable like $_SESSION['myid'].

To fix this immediately, you must extract the specific scalar value from the object using property access syntax. The corrected logic for your current script requires changing how you fetch the data:

session_start();
$name = $_GET["username"];

// Verify the username is not empty to prevent SQL errors
if (empty($name)) {
    exit;
}

$sql = "SELECT id FROM Users WHERE username='$name' LIMIT 1";
$result = mysql_query($sql);

if (!$result) {
    die(mysql_error());
}

$row = mysql_fetch_object($result);

// Extract the 'id' property from the stdClass object
$_SESSION['myid'] = $row->id;

By appending ->id to $row, you extract the integer value stored in that column, which can then be safely cast to a string by PHP when storing it in the session. This is the minimal change required to resolve the immediate crash.

However, relying on this specific snippet reveals three deeper architectural issues that need addressing in any production environment. First, the code uses the mysql_* functions, which were deprecated in PHP 5.5 and completely removed in PHP 7.0. If you are running a modern version of PHP, this script will fail with a fatal error before you even see the object conversion issue. You must migrate to either MySQLi or PDO.

Second, using direct string concatenation for the $name variable creates a critical vulnerability known as SQL Injection. An attacker could craft a URL like ?username=admin' OR '1'='1 to bypass your logic entirely and potentially extract sensitive data. Always parameterize your queries. In MySQLi or PDO, you pass the user input as a bound parameter rather than injecting it directly into the query string.

Third, using mysql_fetch_object() is generally unnecessary when you only need a single scalar value. Using mysql_fetch_assoc() returns an associative array, allowing you to access the ID via $row['id']. Alternatively, using mysql_fetch_row() gives you a numeric array where $row[0] contains the ID. If you are using PDO or MySQLi prepared statements, the fetch methods often return associative arrays by default, making object fetching an optional configuration rather than the norm.

The Modern Approach with Prepared Statements

Here is how you would implement this securely and compatibly using PDO. This approach eliminates the deprecated functions, prevents SQL injection automatically, and handles the data extraction cleanly without needing to manually convert objects to strings.

session_start();

$name = $_GET["username"] ?? '';

if ($name === '') {
    exit;
}

try {
    $pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Prepare the statement with a placeholder for the username
    $stmt = $pdo->prepare("SELECT id FROM Users WHERE username = :username LIMIT 1");
    
    // Execute the statement with the bound parameter
    $stmt->execute(['username' => $name]);

    // Fetch the result as an associative array or object
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $_SESSION['myid'] = $row['id'];
        
        // Optional: Log to file for debugging session assignments
        error_log("Assigned ID " . $_SESSION['myid'] . " to username " . $name);
    } else {
        // Handle the case where the user was not found
        header('Location: /error-user-not-found');
        exit;
    }
} catch (PDOException $e) {
    // Log the error and show a generic message to the user
    error_log($e->getMessage());
    header('Location: /login-error');
    exit;
}

Using PDO::FETCH_ASSOC returns an array where keys match column names, so accessing $row['id'] is straightforward. The LIMIT 1 clause ensures the query stops after finding the first matching row, which is efficient since usernames are unique. This pattern is standard in modern PHP development and aligns with how frameworks like Laravel handle database interactions.

Why This Matters

The transition from extracting properties of a deprecated object to fetching associative arrays or using prepared statements represents a shift toward safer, more maintainable code. The original error was a symptom of trying to store an object where a scalar value was expected, but the root cause was outdated practices that exposed your application to security risks. By adopting PDO and parameterized queries, you ensure that session variables always contain clean, integer IDs rather than complex objects or vulnerable strings.

Our network