print column names

Discussion in 'PHP' started by gilgalbiblewheel, Jul 22, 2008.

  1. #1
    I need to print out the column names of a database table with php.
     
    gilgalbiblewheel, Jul 22, 2008 IP
  2. omgitsfletch

    omgitsfletch Well-Known Member

    Messages:
    1,222
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    145
    #2
    SHOW fields FROM `table_name`
     
    omgitsfletch, Jul 22, 2008 IP
  3. shallowink

    shallowink Well-Known Member

    Messages:
    1,218
    Likes Received:
    64
    Best Answers:
    2
    Trophy Points:
    150
    #3
    This prints out a simple table with field name and type.

    
    $show_sql = "SHOW FIELDS FROM table_name";
    
    echo "<table>";
    $show_result = mysql_query($show_sql);
    while($s_row = mysql_fetch_array($show_result)) {
    
    echo "<tr><td style='width:50pt'><b>$s_row[0]</b><td>$s_row[1]</tr>";
    
    }
    echo "</table>";
    
    PHP:
     
    shallowink, Jul 23, 2008 IP
  4. fallen

    fallen Well-Known Member

    Messages:
    162
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    118
    #4
    to print field names just use:
    
    $sql = "SELECT * FROM sometable";
    $result = mysql_query($sql);
    if (mysql_num_rows($result)){
    	$columns = mysql_num_fields($result);
    	for($i = 0; $i < $columns; $i++) {
    		echo mysql_field_name($result,$i).", ";
    	}
    }
    
    PHP:
    well this is usefull if you do not want to get another query to the database so you can get the field names and then can print the actual results like you do nomaly.
     
    fallen, Jul 23, 2008 IP