Replacing mysql_fetch_field() for column metadata

mysql_fetch_field() belonged to PHP's original MySQL extension and returned metadata about columns in a result set. The extension was removed from PHP 7. Modern applications can use MySQLi result metadata or query MySQL's schema metadata directly.

Migration rule: use MySQLi metadata when you need information about the columns in a specific result set. Use SHOW FULL COLUMNS or INFORMATION_SCHEMA.COLUMNS when you need the table definition itself.

Historical mysql_fetch_field()

<?php
// Historical only: mysql_* was removed from PHP 7.
$result = mysql_query('SELECT * FROM student');
$field = mysql_fetch_field($result);
echo $field->name;
?>

MySQLi: metadata for the result set

<?php
$result = $connection->query(
    'SELECT id, name, class, mark FROM student'
);

foreach ($result->fetch_fields() as $field) {
    echo htmlspecialchars($field->name) . ' - type code: ' . $field->type . '<br>';
}
?>

fetch_fields() returns field objects for the columns in the result. Properties include the column name, original table/name information, length, flags and a MySQL type code.

Table definition with SHOW FULL COLUMNS

SHOW FULL COLUMNS FROM student;

This is often clearer when your goal is to inspect nullability, type, collation, keys, defaults, privileges and extra attributes of a table.

PDO + INFORMATION_SCHEMA

<?php
$sql = 'SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, COLUMN_DEFAULT, EXTRA
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = :schema AND TABLE_NAME = :table
        ORDER BY ORDINAL_POSITION';
$stmt = $dbo->prepare($sql);
$stmt->execute([
    'schema' => 'sql_tutorial',
    'table' => 'student'
]);
$columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

The original page's field-detail purpose is preserved, but current code no longer depends on removed mysql_num_fields() or mysql_field_flags(). Continue with column counts, column names, column types, and column attributes.

Field names · Field types · Field attributes · Number of fields · Student SQL dump

← All PHP & MySQL topics




Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer