PHP 5.4.33 Released

mysql_field_name

(PHP 4, PHP 5)

mysql_field_nameObtiene el nombre del campo especificado de un resultado

Advertencia

Esta extensión está obsoleta a partir de PHP 5.5.0, y será eliminada en el futuro. En su lugar, deberían usarse las extensiones MySQLi o PDO_MySQL. Véase también la guía MySQL: elegir una API y P+F relacionadas para más información. Las alternativas a esta función incluyen:

Descripción

string mysql_field_name ( resource $result , int $field_offset )

mysql_field_name() devuelve el nombre del índice del campo especificado.

Parámetros

result

El resultado resource que está siendo evaluado. Este resultado proviene de una llamada a mysql_query().

field_offset

El número del campo a buscar. El valor de field_offset comienza en 0. Si field_offset no existe, un error de nivel E_WARNING es emitido.

Valores devueltos

El nombre del índice del campo especificado en caso de éxito o FALSE en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de mysql_field_name()

<?php
/* La tabla usuarios consiste de tres campos:
 *   user_id
 *   username
 *   password.
 */
$enlace mysql_connect('localhost''usuario_mysql''contraseña_mysql');
if (!
$enlace) {
    die(
'No se pudo conectar al servidor MySQL: ' mysql_error());
}
$nombre_bd 'mibd';
$bd_seleccionada mysql_select_db($nombre_bd$enlace);
if (!
$bd_seleccionada) {
    die(
"No se pudo establecer $nombre_bd: " mysql_error());
}
$resultado mysql_query('select * from usuarios'$enlace);

echo 
mysql_field_name($resultado0) . "\n";
echo 
mysql_field_name($resultado2);
?>

El resultado del ejemplo sería:

user_id
password

Notas

Nota: Los nombres de los campos devueltos por esta función son sensibles a mayúsculas y minúsculas.

Nota:

Por razones de compatibilidad con versiones anteriores, los siguientes alias obsoletos podrían usarse: mysql_fieldname()

Ver también

add a note add a note

User Contributed Notes 12 notes

up
4
janezr at jcn dot si
8 years ago
This is another variant of displaying all columns of a query result, but with a simplified while loop.

<?
$query
="select * from user";
$result=mysql_query($query);
$numfields = mysql_num_fields($result);

echo
"<table>\n<tr>";

for (
$i=0; $i < $numfields; $i++) // Header
{ echo '<th>'.mysql_field_name($result, $i).'</th>'; }

echo
"</tr>\n";

while (
$row = mysql_fetch_row($result)) // Data
{ echo '<tr><td>'.implode($row,'</td><td>')."</td></tr>\n"; }

echo
"</table>\n"
?>
up
2
anonymous at site dot com
6 years ago
This function is slightly stupid to be honest, why not just make an array of field names... You could consolidate the two of these functions that way and it makes it a lot easier to list them when your script is dynamic.

<?php

   
function mysql_field_array( $query ) {
   
       
$field = mysql_num_fields( $query );
   
        for (
$i = 0; $i < $field; $i++ ) {
       
           
$names[] = mysql_field_name( $query, $i );
       
        }
       
        return
$names;
   
    }
   
   
// Examples of use
   
   
$fields = mysql_field_array( $query );
   
   
// Show name of column 3
   
   
echo $fields[3];
   
   
// Show them all
   
   
echo implode( ', ', $fields[3] );
   
    
// Count them - easy equivelant to 'mysql_num_fields'
   
   
echo count( $fields );

?>
up
1
clinnenb at hotmail dot com
9 years ago
The following will create a PHP array, $array, containing the MySQL query results with array indexes of the same name as field names returned by the MySQL query.

while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $i=0;
    foreach ($line as $col_value) {
        $field=mysql_field_name($result,$i);
        $array[$field] = $col_value;
        $i++;
    }
}
up
2
matteo.cisilino[no_more]cisilino[spm]com
7 years ago
james, why make so difficult when it's very simple :\

$numberfields = mysql_num_fields($res_gb);

   for ($i=0; $i<$numberfields ; $i++ ) {
       $var = mysql_field_name($res_gb, $i);
       $row_title .= $var;
   }

echo $row_title;
up
1
blackjackdevel at gmail dot com
6 years ago
Strangely using an aproach like this:
$res=mysql_query("SELECT * FROM `orders`",$conec) or die (mysql_error());

$fields = mysql_num_fields($res);
$out="";
for ($i = 0; $i < $fields; $i++) {
    $fname=mysql_field_name($res, $i);

}

Outputted the E_Warning:
Warning: mysql_field_name() [function.mysql-field-name]: Field N is invalid for MySQL result index

With a lot of different number at N. But expliciting all fields instead of *. Didn't outputted the error.

It maybe a caracteristic of this mysql database(it is from a open source application) because i never saw this in my own databases. Anyway hope this help if someone face the same strange situation
up
1
jimharris at blueyonder dot co dot uk
9 years ago
The code in the last comment has an obvious mistake in the for loop expression.  The correct expression in the for-loop is $x<$y rather than $x<=$y...

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x<$y; $x++) {
   echo = mysql_field_name($result, $x).'<br>';
}
up
1
matt at iwdt dot net
13 years ago
here's one way to print out a row of <th> tags from a table
NOTE: i didn't test this

$result = mysql_query("select * from table");

for ($i = 0; $i < mysql_num_fields($result); $i++) {
    print "<th>".mysql_field_name($result, $i)."</th>\n";
}

post a comment if there's an error
up
0
bags
4 years ago
When using aliases, it appears impossible to discover the name of the underlying column.
select `ID` as `anAlias` from `aTable` returns 'anAlias' as the mysql_field_name(). I have tried all the mysql_field_xxx() functions and none return the real column name.
up
0
colin dot truran at shiftf7 dot com
9 years ago
T simply itterate through all the field names on a result set try using this.

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x<=$y; $x++) {
    echo = mysql_field_name($result, $x).'<br>';
}

This is useful if you have a result set that joins several tables dynamicaly and you are never sure what all the fields will be when you come to display them.

I suggest you place this within a loop through your result rows and include a field flag check  around the echo to only show certain data types like this.

$y=mysql_num_fields($result);
while ($row=mysql_fetch_array($result)) {
  for ($x=0; $x<=$y; $x++) {
    $fieldname=mysql_field_name($result,$x);
    $fieldtype=mysql_field_type($result, $x);
    if ($fieldtype=='string' && $row[$fieldname]!='')   
       echo $row[$fieldname].' , ';
   }
   echo '<br>';
}
up
0
jason dot chambes at phishie dot net
11 years ago
<?
/*
    By simply calling the searchtable() function
    with these variables it will serach the desired
    database and procude a table for each field that
    there is a match.
*/

function searchtable($host,$user,$pass,$database,$tablename,$userquery)
{
   
$link   = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error());
   
$db     = mysql_select_db($database, $link) or die(mysql_error());
   
$fields = mysql_list_fields($database, $tablename, $link);
   
$cols   = mysql_num_fields($fields);

    for (
$i = 1; $i < $cols; $i++) {
       
$allfields[] = mysql_field_name($fields, $i);
    }
    foreach (
$allfields as $myfield) {
       
$result = mysql_query("SELECT * FROM $tablename WHERE $myfield like '%$userquery%' ");
        if (
mysql_num_rows($result) > 0){
            echo
"<h3>search <i>$database</i> for <i>$userquery</i>, found match(es) in <i>$myfield</i>: </h3>\n";
            echo
"<table border=1 align=\"center\">\n\t<tr>\n";
            for (
$i = 1; $i < $cols; $i++) {
                echo
"\t\t<th";
                if (
$myfield == mysql_field_name($fields, $i)){
                    echo
" bgcolor=\"orange\"> ";
                } else {
                    echo
">";
                }
                echo
mysql_field_name($fields, $i) . "</th>\n";
            }
            echo
"\t</tr>\n";
           
$myrow = mysql_fetch_array($result);
            do {
                echo
"\t<tr>\n";
                for (
$i = 1; $i < $cols; $i++){
                    echo
"\t\t<td> $myrow[$i] &nbsp;</td>\n";
                }
                echo
"\t</tr>\n";
            } while (
$myrow = mysql_fetch_array($result));
            echo
"</table>\n";
        }
    }
}

searchtable($host,$user,$pass,$database,$tablename,$userquery);
?>
up
-1
aaronp123 att yahoo dott comm
11 years ago
You could probably elaborate on this by sending a full sql query to this function...but I titled it simple_query() because it doesn't really allow for joins.  Never the less, if you want to get a quick array full of a single row result set this is painless:

function simple_query($table_name, $key_col, $key_val) {
    // open the db
    $db_link = my_sql_link();
    // query table using key col/val
    $db_rs = mysql_query("SELECT * FROM $table_name WHERE $key_col = $key_val", $db_link);
    $num_fields = mysql_num_fields($db_rs);
    if ($num_fields) {
        // first (and only) row
        $row = mysql_fetch_assoc($db_rs);
        // load up array
        for ($i = 0; $i < $num_fields; $i++) {
            $simple_q[mysql_field_name($db_rs, $i)] = $row[mysql_field_name($db_rs, $i)];
        }
        // and return
        return $simple_q;
    } else {
        // no rows
        return false;
    }
    mysql_free_result($db_rs);
}

**Please note that my_sql_link() is just a function I have to open up a my sql connection.**
up
-1
tiptonentserv at gmail dot com
3 years ago
simple sql to xml converter works with any sql query and returns the name of the table as the root element "row" as each row element and the names of the columns are your children of row. fully tested.

<?php
function sqlToXml($host,$user,$pass,$database,$tablename,$query){

   
$link   = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error());
   
$db     = mysql_select_db($database, $link) or die(mysql_error());
   
   
$result = mysql_query($query);
    if(!
$result){ die('Invalid query: '.mysql_error()); }
   
   
$numOfCols = mysql_num_fields($result);
   
$numOfRows = mysql_num_rows($result);
   
   
$info = mysql_fetch_assoc($result);
   
   
//send headers
   
header('Content-type: text/xml');
   
header('Pragma: public');       
   
header('Cache-control: private');
   
header('Expires: -1');
   
$xml = '<?xml version="1.0" encoding="utf-8"?>';
   
$xml.= "<{$tablename}>";
   
    if(
$numOfRows > 0){
        do {
           
$xml.= "<row>";
            foreach(
$info as $column => $value) {
               
$xml.= "<{$column}>{$value}</{$column}>";
            }
           
$xml.= "</row>";
        }
        while (
$info = mysql_fetch_array($result));
    }
   
$xml.= "</{$tablename}>";
   
   
mysql_free_result($result);   
    return
$xml;
   
}
?>
To Top