Php field names mysql

mysql_field_name

mysql_field_name returns the name of the specified field index.

Parameters

The result resource that is being evaluated. This result comes from a call to mysql_query.

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The name of the specified field index on success or false on failure.

Notes

Note:

Field names returned by this function are case-sensitive.

Note:

For backward compatibility, the following deprecated alias may be used: mysql_fieldname

  • mysql_field_len — Returns the length of the specified field
  • mysql_field_type — Get the type of the specified field in a result

Example of mysql_field_name

Function mysql_field_name:

Original MySQL API Functions

  • mysql_affected_rows
  • mysql_client_encoding
  • mysql_close
  • mysql_connect
  • mysql_create_db
  • mysql_data_seek
  • mysql_db_name
  • mysql_db_query
  • mysql_drop_db
  • mysql_errno
  • mysql_error
  • mysql_escape_string
  • mysql_fetch_array
  • mysql_fetch_assoc
  • mysql_fetch_field
  • mysql_fetch_lengths
  • mysql_fetch_object
  • mysql_fetch_row
  • mysql_field_flags
  • mysql_field_len
  • mysql_field_name
  • mysql_field_seek
  • mysql_field_table
  • mysql_field_type
  • mysql_free_result
  • mysql_get_client_info
  • mysql_get_host_info
  • mysql_get_proto_info
  • mysql_get_server_info
  • mysql_info
  • mysql_insert_id
  • mysql_list_dbs
  • mysql_list_fields
  • mysql_list_processes
  • mysql_list_tables
  • mysql_num_fields
  • mysql_num_rows
  • mysql_pconnect
  • mysql_ping
  • mysql_query
  • mysql_real_escape_string
  • mysql_result
  • mysql_select_db
  • mysql_set_charset
  • mysql_stat
  • mysql_tablename
  • mysql_thread_id
  • mysql_unbuffered_query

Most used PHP functions

  • sandbox (118391575)
  • preg_replace (206883)
  • json_encode (145706)
  • preg_match (135051)
  • unserialize (115758)
  • serialize (111351)
  • hex2bin (101003)
  • uniqid (82090)
  • array (72451)
  • json_decode (61756)
  • iconv (54019)
  • utf8_decode (47300)
  • preg_replace_callback (47044)
  • preg_match_all (45944)
  • str_replace (42721)
  • strtotime (38839)
Читайте также:  Сортировка массива слиянием python

Источник

mysql_field_name

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

Описание

mysql_field_name() возвращает название колонки с указанным индексом.

Список параметров

Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .

Числовое смещение поля. field_offset начинается с 0 . Если field_offset не существует, генерируется ошибка уровня E_WARNING .

Возвращаемые значения

Название поля по указанному индексу в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования mysql_field_name()

/* Таблица пользователей состоит из трёх колонок:
* user_id
* username
* password.
*/
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Ошибка соединения с MySQL: ‘ . mysql_error ());
>
$dbname = ‘mydb’ ;
$db_selected = mysql_select_db ( $dbname , $link );
if (! $db_selected ) die( «Не удалось выбрать базу $dbname : » . mysql_error ());
>
$res = mysql_query ( ‘select * from users’ , $link );

echo mysql_field_name ( $res , 0 ) . «\n» ;
echo mysql_field_name ( $res , 2 );
?>

Результат выполнения данного примера:

Примечания

Замечание: Имена полей, возвращаемые этой функцией являются зависимыми от регистра.

Замечание:

Для обратной совместимости может быть использован следующий устаревший псевдоним: mysql_fieldname()

Смотрите также

  • mysql_field_type() — Возвращает тип указанного поля из результата запроса
  • mysql_field_len() — Возвращает длину указанного поля

User Contributed Notes 12 notes

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.

function mysql_field_array ( $query )

$field = mysql_num_fields ( $query );

$names [] = mysql_field_name ( $query , $i );

$fields = mysql_field_array ( $query );

echo implode ( ‘, ‘ , $fields [ 3 ] );

// Count them — easy equivelant to ‘mysql_num_fields’

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);

while ($row = mysql_fetch_row($result)) // Data
< echo ' ‘.implode($row,’ ‘).»

\n»; >

here’s one way to print out a row of

tags from a table
NOTE: i didn’t test this

$result = mysql_query(«select * from table»);

post a comment if there’s an error

james, why make so difficult when it’s very simple :\

for ($i=0; $i $var = mysql_field_name($res_gb, $i);
$row_title .= $var;
>

The code in the last comment has an obvious mistake in the for loop expression. The correct expression in the for-loop is $x

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x echo = mysql_field_name($result, $x).’
‘;
>

/*
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 «

search $database for $userquery, found match(es) in $myfield:

\n»;
echo «

\n\t \n»;
for ($i = 1; $i < $cols; $i++) echo "\t\t if ($myfield == mysql_field_name($fields, $i)) echo " bgcolor=\"orange\"> «;
> else echo «>»;
>
echo mysql_field_name($fields, $i) . «

\n»;
>
echo «\t

\n»;
$myrow = mysql_fetch_array($result);
do echo «\t

\n»;
for ($i = 1; $i < $cols; $i++)echo "\t\t

\n»;
>
echo «\t

\n»;
> while ($myrow = mysql_fetch_array($result));
echo «

$myrow[$i]  

\n»;
>
>
>

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.

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 )

$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 .= » < < $tablename >>» ;

if( $numOfRows > 0 ) <
do <
$xml .= «» ;
foreach( $info as $column => $value ) <
$xml .= » < < $column >> >» ;
>
$xml .= «
» ;
>
while ( $info = mysql_fetch_array ( $result ));
>
$xml .= « >» ;

mysql_free_result ( $result );
return $xml ;

Источник

mysql_field_name

Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:

Описание

mysql_field_name() возвращает название колонки с указанным индексом.

Список параметров

Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .

Числовое смещение поля. field_offset начинается с 0. Если field_offset не существует, генерируется ошибка уровня E_WARNING .

Возвращаемые значения

Название поля по указанному индексу в случае успеха или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования mysql_field_name()

/* Таблица пользователей состоит из трёх колонок:
* user_id
* username
* password.
*/
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Ошибка соединения с MySQL: ‘ . mysql_error ());
>
$dbname = ‘mydb’ ;
$db_selected = mysql_select_db ( $dbname , $link );
if (! $db_selected ) die( «Не удалось выбрать базу $dbname : » . mysql_error ());
>
$res = mysql_query ( ‘select * from users’ , $link );

echo mysql_field_name ( $res , 0 ) . «\n» ;
echo mysql_field_name ( $res , 2 );
?>

Результат выполнения данного примера:

Примечания

Замечание: Имена полей, возвращаемые этой функцией являются регистро-зависимыми.

Замечание:

Для обратной совместимости может быть использован следующий устаревший псевдоним: mysql_fieldname()

Смотрите также

  • mysql_field_type() — Возвращает тип указанного поля из результата запроса
  • mysql_field_len() — Возвращает длину указанного поля

Источник

mysql_field_name Functions to get name of the fields of a table

By using the simple query ‘SHOW COLUMNS FROM table’ we can get the column names. This query will list out the column names. To display all the records of a table we will use this to show column names. Here is the sample code.

$result = $dbo->query("SHOW COLUMNS from student"); echo ""; //// Display column head /// while ($row = $result->fetch(PDO::FETCH_NUM)) < echo "$row[0]"; > 

Above code will display the columns but we don’t know how many columns are present. (We can keep a counter inside PHP while loop but let us know by using query.) Here is the query with code to display number of columns.

$count=$dbo->prepare("select * from student"); $count->execute(); //echo "Number of Columns : ". $count->columnCount(); $no_of_columns=$count->columnCount(); // store it in a variable 

Above code we used and prepared a full code to display all the records present in a table. We have only provided table name as input to the script, column names with records are displayed on its own. Here is the complete code.

query("SHOW COLUMNS from student"); echo ""; //// Display column head /// while ($row = $result->fetch(PDO::FETCH_NUM)) < echo ""; > ///Find out number of columns //// $count=$dbo->prepare("select * from student"); $count->execute(); //echo "Number of Columns : ". $count->columnCount(); $no_of_columns=$count->columnCount(); // store it in a variable ///// Header is over, now show records //// $data=$dbo->prepare("select * from student"); $data->execute(); while($result=$data->fetch(PDO::FETCH_NUM))< echo ""; for($j=0;$j<$no_of_columns;$j++)< echo ""; > // end of for loop displaying one row echo ""; > // end of while loop echo "
$row[0]
$result[$j]
"; ?>

This old MySQL extension was deprecated in PHP 5.5.0 and was removed in PHP 7

Use mysqli_fetch_field_direct() in place of mysql_field_name().

Table records with Column Head

mysql_field_name

The function mysql_field_name returns the name of the field we supply as field index. For example let us use one simple table student where we have four columns ID, name, class & mark. These four columns name we have specified while creating or modifying the table. We can get these table names by using mysql_field_name function.

 mysql_field_name ( $result , int $field_index ) 

As you have seen this function takes two inputs, one is the result of a mysql_query() function, the other one is the index of the field. The index of the first field is 0 ( zero ) and for second field it is 1. So if we want the header ( column name ) of fourth field then we have to use 3 as index in the mysql_field_name.

If we don’t know the index of the field or don’t know how many fields are there in a table then we can use mysql_num_fields function. Once we know the total number of fields in a table then we can use them as field index to get the field name.

Here is the code for displaying the field names of any table. ( It is assumed that you have active connection to mysql and database selection is done )

 $q=mysql_query("select * from student order by id "); $num_fields = mysql_num_fields($q); echo ""; for ($i=0; $i < $num_fields; $i++) < echo ''; > echo "
'.mysql_field_name($q, $i).'
";

The output of the above code is here for our student table.

Now let us add data also here and display all the records along with the table headers , here is the full code.

 $q=mysql_query("select * from student order by id "); $num_fields = mysql_num_fields($q); echo ""; ////Field name display starts//// for ($i=0; $i < $num_fields; $i++) < echo ''; > /// Field name display ends ///// /// Data or Record display starts ///// while($nt=mysql_fetch_row($q))< echo ""; while (list ($key, $val) = each ($nt))$val";> echo ""; > ////// End of data display /////// echo "
'.mysql_field_name($q, $i).'
";

plus2net.com

Источник

Оцените статью