Jump to content

[SOLVED] HELP!: Echo MySQL field names to XML-structure


Kenwio

Recommended Posts

Hi!

 

I want to output the field names of a MySQL database table to an XML-structure through PHP. I've managed to echo the field names, but all the field names are echoed as ONE OBJECT.

Here's the PHP code:

<?php

require_once("connection.php");
    
        $res = mysql_query('SELECT * FROM stations');
        // This begins the XML-response
$return = "<stations>";
$return .= "<station>";
$numberfields = mysql_num_fields($res);

for ($i=0; $i<$numberfields ; $i++ ) {
             $var = mysql_field_name($res, $i);
             $return .= "<station_id>".$var->station_id."</station_id>";
}

$return .= "</station>";
        // This ends the XML-response
$return .= "</stations>";
echo $return;
?>

 

...and here's the result in a browser:

station_idstation_namestation_typestation_frequencystation_location... etc

 

Now, I now that mysql_fetch_object works on rows in a database, but does it work with actual field names? Is it possible to use mysql_fetch_object on field/column names when using mysql_field_name?

 

TABLE NAME:

- stations

 

COLUMN NAMES OF stations:

- station_id

- station_name

- station_type... etc

 

WAMP5 v1.7.4, MySQL v5.0.45

 

Please if you have any ideas, Post-it!

//Kenwio

This is solved.

Instead of:

    
<?php
     $res = mysql_query('SELECT * FROM stations');
   
     $return = "<stations>";
     $return .= "<station>";
     $numberfields = mysql_num_fields($res);

     for ($i=0; $i<$numberfields ; $i++ ) {
        $var = mysql_field_name($res, $i);
        $return .= "<station_id>".$var."</station_id>";
     }
     $return .= "</station>";
     $return .= "</stations>"; 
     echo $return;
?>

I use:

    
<?php
     $res = mysql_query('SELECT * FROM stations');
   
     $return = "<stations>";
     $numberfields = mysql_num_fields($res);

     for ($i=0; $i<$numberfields ; $i++ ) {
        $var = mysql_field_name($res, $i);
        $return .= "<station><station_id>".$var."</station_id></station>";
     }

     $return .= "</stations>"; 
     echo $return;
?>

 

Now each field columns name is treated as ONE OBJECT.

 

Hope this will help someone in the future...

//Kenwio

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.