Louie Jay Jayme
Louie Jay Jayme

Reputation: 179

how to query the column names of a table

Hi guys i need help about displaying a column name of a specific table example i have a table named account and it has account_id, first_name, last_name and stuffs like that what i need is to display the account_id, first_name, last_name and so on and not the data inside that column really need your help.. thanks :)

SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'mydatabase'

that's the code i found while i was researching for answers but i don't know how to excecute this one.. i really have no idea how would i use this to display the column name..

Upvotes: 0

Views: 193

Answers (6)

tinybai
tinybai

Reputation: 916

$result = mysql_query("SHOW COLUMNS FROM sometable");
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        print_r($row);
    }
}

the result maybe:

Array
(
    [Field] => id
    [Type] => int(7)
    [Null] =>
    [Key] => PRI
    [Default] =>
    [Extra] => auto_increment
)

Upvotes: 2

bear
bear

Reputation: 11625

It is recommended to use MySQLi over MySQL in terms of PHP.

You can use mysqli_fetch_field()

$query = "SELECT blah from blah ORDER BY blah LIMIT 5";

if ($result = $mysqli->query($query)) {

/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);
    }

    $result->close();
}

Upvotes: 0

user1726343
user1726343

Reputation:

How about using DESCRIBE

DESCRIBE tablename;

Try it here: http://sqlfiddle.com/#!2/a2581/2823/0

Upvotes: 2

NobleUplift
NobleUplift

Reputation: 6024

SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME='table';

This should take the columns right from the information schema.

Upvotes: 0

John Woo
John Woo

Reputation: 263883

i need is to display the account_id, first_name, last_name and so on and not the data inside that column

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME  = 'B'

Upvotes: 0

anon
anon

Reputation:

$query= "SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'mytablename' ";

$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {echo "$row[acount_id] $row[first_name] $row[last_name]";}

Use the above to echo all three data from database

Upvotes: -1

Related Questions