Walrus
Walrus

Reputation: 20444

PHP mySQL get table headers function

I'm trying to build a PHP function that allows me to have an array of the headers of MySQL database for finding a particular field.

function table($tablename,$id) {
  $post = mysql_query("SELECT * FROM $tablename WHERE ID = '$id'");
}

How would I then output the table headers as effective miniature queries for the row in question.

eg. $post->title, $post->timestamp, $post->field4

Upvotes: 1

Views: 10131

Answers (4)

Will Morgan
Will Morgan

Reputation: 4490

You can get just the column names by executing this:

DESCRIBE `MyTable`;

It will return a result set that contains Field, Type, Key, etc.

$query = mysql_query("DESCRIBE `MyTable`");
while($result = mysql_fetch_assoc($query)) {
    echo $result['Field'] . "\n";
}

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

A simple PHP Script to fetch the field names in MySQL:

<?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 helps! Taken from php.net documentation.

Upvotes: 3

Corsair
Corsair

Reputation: 1044

How about mysql_fetch_assoc($post)?

To get all field names int a seperate array:

$post = mysql_fetch_assoc($post);
$fields = array();

foreach($post as $title => $value){
    $fields[] = $title;
}

You can use this in a while loop to go through all rows and get theri field values(as well as their names):

while($p = mysql_fetch_assoc($post)){

    $title = $p['title'];
    $timestamp = $p['timestamp'];

    //And so on...
}

Edit: And Pierpaolo is right, you should use another mysql implementation as the old one is gonna be removed in PHP 5.5/5.6 or a bit later...

Upvotes: 2

HBv6
HBv6

Reputation: 3537

You need MySQLi or PDO_MySQL, but in your case:

while ($row = mysql_fetch_assoc($post)) {
    echo $row['title'];
}

Documentation

Remember that the use of mysql_* function is discouraged.

Upvotes: 3

Related Questions