rune_sm Posted April 19, 2007 Share Posted April 19, 2007 Hey everyone I'm making a php-script that I can use to access any Mysql table i use. That's why I don't know the names of the columns. Sometimes it's a table containing new, sometimes url-links to pictures. The script outputs an xml file to flash, and I usually do something like this: <?php // Database iinformation $db_host="myhost.dk"; $db_user="myuser"; $db_name="mydbname"; $db_password="mypass"; mysql_pconnect($db_host, $db_user, $db_password); mysql_select_db($db_name); // Select data in database $result = mysql_query("select * from news"); // Loop through it while ($row = mysql_fetch_array($result)) { print('<headline>'.$row["headline"].'</headline>'); print('<date>'.$row["date"].'</date>'); print('<text>'.$row["headline"].'</text>'); } ?> But when I don't know how many columns I have in my table or what their names are, I cannot figure it out. What I want to do in my loop is something like this: // Loop through it while ($row = mysql_fetch_array($result)) { print('<'.$row["name-of-column1"].'>'); print($row["data-in-column1"]); print('<'.$row["name-of-column1"].'>'); } Link to comment https://forums.phpfreaks.com/topic/47761-get-mysql-column-names/ Share on other sites More sharing options...
bubblegum.anarchy Posted April 20, 2007 Share Posted April 20, 2007 string mysql_field_name ( resource result, int field_offset ) <?php /* The users table consists of three fields: * user_id * username * password. */ $link = @mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect to MySQL server: ' . mysql_error()); } $dbname = 'mydb'; $db_selected = mysql_select_db($dbname, $link); if (!$db_selected) { die("Could not set $dbname: " . mysql_error()); } $res = mysql_query('select * from users', $link); echo mysql_field_name($res, 0) . "\n"; echo mysql_field_name($res, 2); ?> The above example will output: user_id password and use int mysql_num_fields ( resource result ) for a field count Link to comment https://forums.phpfreaks.com/topic/47761-get-mysql-column-names/#findComment-233726 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.