Current Location: Home> Latest Articles> How to Use the mysql_field_name Function to Get All Column Names in a Database Table?

How to Use the mysql_field_name Function to Get All Column Names in a Database Table?

gitbox 2025-09-18
<span class="hljs-meta"><?php
// This article explains how to use the mysql_field_name function in PHP to retrieve all column names from a database table.
<p>// Example of connecting to a database<br>
$host = 'localhost';<br>
$user = 'root';<br>
$password = '123456';<br>
$dbname = 'testdb';</p>
<p>$conn = mysql_connect($host, $user, $password);<br>
if (!$conn) {<br>
die('Database connection failed: ' . mysql_error());<br>
}</p>
<p>mysql_select_db($dbname, $conn);<br>
mysql_query("SET NAMES utf8");</p>
<p>>?><span></p>
<hr>
<h2>How to Use the mysql_field_name Function to Get All Column Names in a Database Table?</h2>
<p>When connecting to a MySQL database using PHP, sometimes we need to retrieve the names of all columns in a table for dynamic processing. Although the <strong>mysql_field_name</strong> function is deprecated and it is recommended to use MySQLi or PDO, we will still demonstrate its usage here for understanding the process of obtaining column names.</p>
<h3>Steps:</h3>
<ol>
<li>First, use <code>mysql_query

With the code above, the $fields array stores the names of all columns in the table, making it easy to iterate through and use them in your program.

Notes:

  • The mysql_* series of functions have been removed in PHP 7 and above, so it is recommended to use MySQLi or PDO instead.
  • When using MySQLi, you can get column information via mysqli_fetch_fields() or mysqli_fetch_field_direct().
  • This example is only suitable for legacy projects. When updating code, consider using modern database interfaces.

In summary, the mysql_field_name function allows quick retrieval of a field name from a result set, but in actual projects, it is advisable to avoid deprecated APIs and use safer, more powerful extensions instead.