downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mysql_fetch_lengths> <mysql_fetch_assoc
Last updated: Fri, 20 Nov 2009

view this page in

mysql_fetch_field

(PHP 4, PHP 5)

mysql_fetch_field Pobiera z wyniku informacje o kolumnie i zwraca jako obiekt

Opis

object mysql_fetch_field ( resource $wynik [, int $ ofset_pola ] )

Zwraca obiekt zawierający informacje o polu.

mysql_fetch_field() pozwala uzyskać informacje o polach w danym wyniku zapytania. Jeżeli ofset pola nie został podany, zwracane zostanie następne pole nie pobrane jeszcze przez mysql_fetch_field().

Właściwości obiektu:

  • name - nazwa kolumny
  • table - nazwa tabeli do której należy kolumna
  • max_length - maksymalna długość kolumny
  • not_null - 1 jeżeli pole nie może być puste (NULL)
  • primary_key - 1 jeżeli kolumna jest kluczem podstawowym
  • unique_key - 1 jeżeli kolumna jest kluczem unikatowym
  • multiple_key - 1 jeżeli kolumna jest kluczem nieunikatowym
  • numeric - 1 jeżeli kolumna jest liczbowa
  • blob - 1 jeżeli kolumna jest typu BLOOB
  • type - typ kolumny
  • unsigned - 1 jeżeli kolumna jest bez znaku (plus lub minus)
  • zerofill - 1 jeżeli kolumna jest wypełniona zerami

Przykład #1 mysql_fetch_field()

<?php
mysql_connect
('localhost','uzytkownik','haslo');
    or die (
'Nie można się połączyć');
mysql_select_db('baza');
$result mysql_query('select * from tabela')
    or die(
'Zapytanie zakończone niepowodzeniem');
/* pobieramy dane kolumny */
$i 0;
while (
$i mysql_num_fields($result)) {
    echo 
"Informacje o kolumnie $i:<br />\n";
    
$meta mysql_fetch_field($result);
    if (!
$meta) {
        echo 
"Informacje niedostępne<br />\n";
    }
    echo 
"<pre>
blob:         
$meta->blob
max_length:   
$meta->max_length
multiple_key: 
$meta->multiple_key
name:         
$meta->name
not_null:     
$meta->not_null
numeric:      
$meta->numeric
primary_key:  
$meta->primary_key
table:        
$meta->table
type:         
$meta->type
unique_key:   
$meta->unique_key
unsigned:     
$meta->unsigned
zerofill:     
$meta->zerofill
</pre>"
;
    
$i++;
}
mysql_free_result($result);
?>

Patrz także: mysql_field_seek().



mysql_fetch_lengths> <mysql_fetch_assoc
Last updated: Fri, 20 Nov 2009
 
add a note add a note User Contributed Notes
mysql_fetch_field
mewsterus at yahoo dot com
07-Jul-2009 06:18
A nice function to return an array of all fields for a particular table. I've added a few very useful properties to the spec:

'len', which is supplied by the mysql_field_len() function.
'definition', which is a column_definition which could be used to initialize the table.
'auto_increment', which is 1 if the field is auto_increment.

<?php
function mysql_fetch_fields($table) {
       
// LIMIT 1 means to only read rows before row 1 (0-indexed)
       
$result = mysql_query("SELECT * FROM $table LIMIT 1");
       
$describe = mysql_query("SHOW COLUMNS FROM $table");
       
$num = mysql_num_fields($result);
       
$output = array();
        for (
$i = 0; $i < $num; ++$i) {
               
$field = mysql_fetch_field($result, $i);
               
// Analyze 'extra' field
               
$field->auto_increment = (strpos(mysql_result($describe, $i, 'Extra'), 'auto_increment') === FALSE ? 0 : 1);
               
// Create the column_definition
               
$field->definition = mysql_result($describe, $i, 'Type');
                if (
$field->not_null && !$field->primary_key) $field->definition .= ' NOT NULL';
                if (
$field->def) $field->definition .= " DEFAULT '" . mysql_real_escape_string($field->def) . "'";
                if (
$field->auto_increment) $field->definition .= ' AUTO_INCREMENT';
                if (
$key = mysql_result($describe, $i, 'Key')) {
                        if (
$field->primary_key) $field->definition .= ' PRIMARY KEY';
                        else
$field->definition .= ' UNIQUE KEY';
                }
               
// Create the field length
               
$field->len = mysql_field_len($result, $i);
               
// Store the field into the output
               
$output[$field->name] = $field;
        }
        return
$output;
}

// Example:
mysql_connect('localhost', 'user', 'pass');
mysql_select_db('database');
$fields = mysql_fetch_fields('table');
foreach (
$fields as $key => $field) {
        echo
$field->name . ' ' . $field->definition . "\n";
}

// May output:
// field1 char(8)
// field2 int PRIMARY KEY
// field3 int AUTO_INCREMENT UNIQUE KEY
// field4 mediumtext NOT NULL DEFAULT 'I\'m a little teapot'
?>
TALU
04-Feb-2009 04:16
XML generation.

Bit of a security risk allowing parameters to select db and table on live server (unless user is restricted or replace the $_GET with fixed value.)

Outputs xml with standard format for <config> part to generate forms in flash.

<?php
   
//
    //    makeXML.php?db=dbname&table=tablename
    //
   
   
set_time_limit(300);
       
   
$host = "localhost";
   
$user = "root";
   
$password = "root";
   
   
$database = $_GET['db'];   
   
$table = $_GET['table'];
   
   
mysql_connect($host,$user,$password);
    @
mysql_select_db($database) or die( "Unable to select database");
   

   
$querytext="SELECT * FROM ".$table
   
$result=mysql_query($querytext);
   
    if (
$result){
       
$num=mysql_num_rows($result);
    }else{
       
$num=0;
    }
   
?>
<?php
    header
('Content-Type: text/xml');
     echo
"<?xml version='1.0'?>";
    
     if (
$num > 0){
 
?>
<<?php  echo $table?>>
    <config>
        <?php
           
// Display number of fields
           
echo "<numFields>".mysql_num_fields($result)."</numFields>";
           
$i = 0;
           
$primaryKey = "";
           
$nameArray = array();
           
$maxLengthArray = array();
           
$typeArray = array();
            while (
$i < mysql_num_fields($result)) {
               
$meta = mysql_fetch_field($result, $i);
               
$nameArray[$i] = $meta->name;
               
$maxLengthArray[$i] = $meta->max_length;
               
$typeArray[$i] = $meta->type;
                if (
$meta->primary_key){
                   
$primaryKey = $meta->name;
                }
               
$i++;
            }
           
$i = 0;
            echo
"<fieldNames>";
            while (
$i < count($nameArray)) {
                echo
"<field".$i.">".$nameArray[$i]."</field".$i.">";
               
$i++;
            }
            echo
"</fieldNames>";
           
$i = 0;
            echo
"<fieldMaxLength>";
            while (
$i < count($maxLengthArray)) {
                echo
"<field".$i.">".$maxLengthArray[$i]."</field".$i.">";
               
$i++;
            }
            echo
"</fieldMaxLength>";
           
$i = 0;
            echo
"<fieldType>";
            while (
$i < count($typeArray)) {
                echo
"<field".$i.">".$typeArray[$i]."</field".$i.">";
               
$i++;
            }
            echo
"</fieldType>";
       
?>
        <primaryKey><?php  echo $primaryKey?></primaryKey>
        <numRecords><?php  echo $num?></numRecords>
    </config>
<?php 
    $i
=0;
    while (
$i < $num) {
       
$ID=mysql_result($result,$i,"ID");
       
$value=mysql_result($result,$i,"value");
       
$title=mysql_result($result,$i,"title");
       
$description=mysql_result($result,$i,"description");
?>
    <row>
        <ID><?php  echo $ID?></ID>
        <weighting><?php  echo $value?></weighting>
        <title><?php  echo $title?></title>
        <description><?php  echo $description?></description>
    </row>
<?php
        $i
= $i + 1;
    }
?>
</<?php  echo $table?>>

<?php
   
}
?>
php [spat] hm2k.org
04-Nov-2008 11:22
An improvement on the earlier mysql_column_exists function.

<?php

function mysql_column_exists($table_name, $column_name, $link=false) {
   
$result = @mysql_query("SHOW COLUMNS FROM $table_name LIKE '$column_name'", $link);
    return (
mysql_num_rows($result) > 0);
}

?>
jorachim at geemail dot com
25-Sep-2008 08:09
If you want the fields in a table, a simple DESCRIBE query will work:

<?php
$query
="DESCRIBE Users";
$result = mysql_query($query);

echo
"<ul>";

while(
$i = mysql_fetch_assoc($result))
     echo
"<li>{$i['Field']}</li>";

echo
"</ul>";
?>

Should do the trick.
david at vitam dot be
10-Jun-2008 12:57
A little function to help coders to distinct the tablename from a multiselect query where some fields has the same name in differents tables.

<?php
public function sql($sql) {
   
$T_Return=array();
   
$result=@mysql_query($sql);
   
   
$i=0;
    while (
$i < mysql_num_fields($result)) {           
       
$fields[]=mysql_fetch_field($result, $i);
       
$i++;
    }
   
    while (
$row=mysql_fetch_row($result)) {               
       
$new_row=array();
        for(
$i=0;$i<count($row); $i++) {
           
$new_row[ $fields[$i]->table][$fields[$i]->name]=$row[$i];
        }
       
$T_Return[]=$new_row;
    }

   
    return
$T_Return;
}
?>
dheep
04-Jun-2008 03:56
Simple PHP script for displaying the field names. Presuming the database is seleected already.

<?php
$sql
= "SELECT * FROM table_name;";
$result = mysql_query($sql);
$i = 0;
while(
$i<mysql_num_fields($result))
{
 
$meta=mysql_fetch_field($result,$i);
  echo
$i.".".$meta->name."<br />";
 
$i++;
}
?>

OUTPUt:
0.id
1.todo
2.due date
3.priority
4.type
5.status
6.notes

hope this is useful.
Nick Baicoianu
15-Sep-2005 06:18
Be sure to note that $max_length is the length of the longest value for that field in the returned dataset, NOT the maximum length of data that column is designed to hold.
php at brayra dot com
22-Mar-2002 12:09
I needed to get the field information and the enum/set values. Here is the function I created to expand the object returned by mysql_fetch_field. I also, decided to return all the fields for a table in an array of field objects by "name" and position much like mysql_fetch_array does.

You could test it by using:

<?php
$myfields
= GetFieldInfo('test_table');
print
"<pre>";
print_r($myfields);
print
"</pre>";
?>


The field objects now have 'len', 'values' and 'flags' parameters.
NOTE: 'values' only has data for set and enum fields.

<?php
//This assumes an open database connection
//I also use a constant DB_DB for current database.
function GetFieldInfo($table)
{
  if(
$table == '') return false;
 
$fields = mysql_list_fields(DB_DB, $table);
  if(
$fields){
   
$columns = mysql_query('show columns from ' . $table);
    if(
$columns){
     
$num = mysql_num_fields($fields);
      for(
$i=0; $i < $num; ++$i){
       
$column = mysql_fetch_array($columns);
       
$field = mysql_fetch_field($fields, $i);
       
$flags = mysql_field_flags($fields, $i);
        if(
$flags == '') $flags=array();
        else
$flags = explode(' ',$flags);
        if (
ereg('enum.(.*).',$column['Type'],$match))
         
$field->values = explode(',',$match[1]);
        if (
ereg('set.(.*).',$column['Type'],$match))
         
$field->values = explode(',',$match[1]);
        if(!
$field->values) $field->values = array();
       
$field->flags = $flags;
       
$field->len = mysql_field_len($fields, $i);
       
$result_fields[$field->name] = $field;
       
$result_fields[$i] = $field;
      }
     
mysql_free_result($columns);
    }
   
mysql_free_result($fields);
    return
$result_fields;
  }
  return
false;
}
?>

hope someone else finds this useful.
krang at krang dot org dot uk
10-Mar-2002 02:12
The field type returns what PHP classifies the data found in the field, not how it is stored in the database; use the following example to retrieve the MySQL information about the field....

<?php
$USERNAME
= '';
$PASSWORD = '';

$DATABASE = '';
$TABLE_NAME = '';

mysql_connect('localhost', $USERNAME, $PASSWORD)
    or die (
"Could not connect");

$result = mysql_query("SHOW FIELDS FROM $DATABASE.$TABLE_NAME");

$i = 0;

while (
$row = mysql_fetch_array($result)) {
  echo
$row['Field'] . ' ' . $row['Type'];
}
?>

mysql_fetch_lengths> <mysql_fetch_assoc
Last updated: Fri, 20 Nov 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites