Replacing mysql_field_name() for column names

mysql_field_name() returned the name of a result-set column from the removed PHP MySQL extension. Current code can obtain column names from the database schema or from result metadata.

Historical mysql_field_name()

<?php
// Historical only.
$q = mysql_query('SELECT * FROM student ORDER BY id');
$name = mysql_field_name($q, 0);
echo $name;
?>

Column names from SHOW COLUMNS

SHOW COLUMNS FROM student;

PDO: build a heading row from schema metadata

<?php
$columns = $dbo->query('SHOW COLUMNS FROM student');
echo '<tr>';
foreach ($columns as $column) {
    echo '<th>' . htmlspecialchars($column['Field']) . '</th>';
}
echo '</tr>';
?>

PDO columnCount() for a result

<?php
$stmt = $dbo->query(
    'SELECT id, name, class, mark FROM student'
);
echo 'Number of columns: ' . $stmt->columnCount();
?>

MySQLi fetch_fields()

<?php
$result = $connection->query(
    'SELECT id, name, class, mark FROM student ORDER BY id'
);
echo '<tr>';
foreach ($result->fetch_fields() as $field) {
    echo '<th>' . htmlspecialchars($field->name) . '</th>';
}
echo '</tr>';
?>

Column names displayed from the student table

The original goal—using field names as table headings—is preserved without mysql_num_fields(), mysql_fetch_row(), or PHP's removed each() function.

Number of fields · Column metadata · Field types · Student SQL dump · MySQLi overview

← 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