0

I want to convert my code from working with mysql to pdo. and i was looking for an equivalent function for mysql_field_name but i didn't find any, except this function PDOStatement::getColumnMeta, but PHP documentation say it's "EXPERIMENTAL" and it won't work with future release of PHP. so i did this work.

assuming i have this table

id         name        age       city
1          ad          25         a      
2          im          23         b
3          sh          21         c 

and i wanna select only the name and city

 name       city
  ad          a      
  im          b
  sh          c 

    $link = new PDO("mysql:host=localhost;dbname=db_name;charset=utf8",user,pass);
    $link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query="SELECT name,city FROM  table" ;
    $result = link->prepare($query);
    $result->execute();
    $result ->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result as $value){
        $tablename =array_keys($value);
    }

    echo "<table><tr>";
    foreach ($tablename  as $key)
        echo "<td>".$key."</td>";
    echo "</tr></table>";

i'm not sure if this's the right way to do it. or if there's a PDO function can do this work

Adsteine
  • 1
  • 1
  • 2

3 Answers3

2

You can get column name like this

 foreach ($result as $row){
    foreach($row as $col_name => $val)
     {
     echo "$col_name == $val<br />";    
     }
    echo"Next Row<br />";
 }
ManiMuthuPandi
  • 1,594
  • 2
  • 26
  • 46
0

Assuming you have table called table

$select = $db->query('SELECT * FROM table');

$total_column = $select->columnCount();
var_dump($total_column);

for ($counter = 0; $counter < $total_column; $counter ++) {
    $meta = $select->getColumnMeta($counter);
    $column[] = $meta['name'];
}

$column will contain complete list of columns, and column meta is a function which will help you to get column properties.

Thanks Amit

Amit Shah
  • 1,380
  • 1
  • 10
  • 19
-1
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
1990rk4
  • 728
  • 11
  • 21