select and echo a single field from mysql db using PHP

select and echo a single field from mysql db using PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Why mysql_query Returns a Resource ID and How to Fix It

When you execute a query like SELECT title FROM events WHERE id = '1', the MySQL connection doesn't immediately return the data. Instead, it establishes a link to the server and hands back a "resource." In older PHP versions using the deprecated mysql_* extension, this resource is an integer ID (e.g., Resource id #19). Printing this ID directly is not useful; it tells you the query was accepted by the server but doesn't expose the actual data.

To retrieve the value of a specific column from a single row, you must fetch the result set into PHP memory before echoing it. The code snippet you provided attempts to echo the resource object itself rather than the content within that resource. This is why you see Resource id #19 in your browser output.

Fetching Single Row Data Correctly

The most straightforward way to handle a single-row query is using mysql_fetch_assoc(). This function takes the result resource and returns an associative array containing the column names as keys. If you only need the title, you can access it directly via that key.

However, there is a critical flaw in your original code: SQL Injection. You are interpolating user input ($_GET['field'] and $_GET['id']) directly into the query string. An attacker could pass id=' OR '1'='1 to bypass authentication or inject malicious SQL commands.

The mysql_* extension is deprecated and removed in PHP 7.0+. Even if you were using it, never trust user input for column names (like $field) because that requires dynamic execution. You should hardcode column names in the query string and use prepared statements for values.

Here is how to achieve the same result using the modern mysqli extension with proper security:

<?php
// Connect to the database
$mysqli = new mysqli("localhost", "user", "password", "database");

// Retrieve and sanitize the ID (assuming integer)
$eventid = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if ($eventid === false) {
    die('Invalid event ID.');
}

// Hardcode the column name to prevent SQL injection on dynamic fields
// If you truly need dynamic columns, use mysqli_fetch_field() or prepared statements carefully
$field = 'title'; 

$sql = "SELECT {$field} FROM `events` WHERE `id` = ?";
$stmt = $mysqli->prepare($sql);

if (!$stmt) {
    die('Prepare failed: ' . $stmt->error);
}

// Bind the ID to the placeholder
$stmt->bind_param("i", $eventid);
$stmt->execute();

$result = $stmt->get_result();

// Fetch a single row as an associative array
$row = $result->fetch_assoc();

if ($row) {
    echo $row['title'];
} else {
    echo 'No record found.';
}

$stmt->close();
$mysqli->close();
?>

Using PDO for Advanced Scenarios

If your application requires more robust error handling or you are working within the Laravel ecosystem, PDO is the preferred interface. It offers a consistent API across different database drivers and supports named parameters which can make queries more readable.

<?php
$dsn = 'mysql:host=localhost;dbname=events;charset=utf8mb4';
$username = 'user';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);

    // Use a named parameter for safety
    $eventid = (int)$_GET['id']; 
    $field = 'title'; // Hardcoded column name

    $stmt = $pdo->prepare("SELECT :field FROM events WHERE id = :id");
    $stmt->execute([':field' => $field, ':id' => $eventid]);
    
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($row) {
        echo htmlspecialchars($row['title']); // Always escape output to prevent XSS
    } else {
        echo 'Data not found.';
    }
} catch (PDOException $e) {
    // Log the error, do not expose raw stack trace to users
    error_log($e->getMessage());
    echo 'Database connection failed.';
}
?>

Best Practices Summary

  1. Never Echo Resources: Always fetch data using fetch_assoc(), fetch_all(), or fetchColumn() before outputting values.
  2. Avoid Deprecated Functions: Stop using mysql_query immediately. It is insecure and incompatible with modern PHP versions.
  3. Sanitize Inputs: Validate IDs strictly as integers. Never pass user input into the column name portion of a SQL query without strict validation, though hardcoding the column is safer.
  4. Escape Output: When echoing database content (like titles), use htmlspecialchars() to prevent Cross-Site Scripting (XSS) attacks if the data contains scripts.

By shifting from resource-based handling to explicit fetching and adopting prepared statements, you ensure your application remains secure, compatible with current PHP standards, and resilient against common injection vulnerabilities. If you are building a full-stack application or need deeper integration with modern frameworks like Laravel, consider how these database patterns translate into Eloquent models or query builders for even cleaner code.

Our network