PHP-PDO 从数据库中获取元数据 [英] PHP- PDO get metadata from database

查看:88
本文介绍了PHP-PDO 从数据库中获取元数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从带有表朋友"的数据库中获取元数据

I want to get the metadata from a database with a table 'friends'

id name
1  Herbert
2  LG
3  Levins

这是我试图获取数据的代码.

Here is the code I was trying to get the data.

<?php

    $dsn = 'mysql:host=localhost;dbname=postgre';
$username = 'root';
$password = '';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
); 

    $db = new PDO($dsn, $username, $password, $options);

 $stmt = $db->query("SELECT * FROM friends");
$cnt_columns = $stmt->columnCount();
for($i = 0; $i < $cnt_columns; $i++) {
  $metadata = $stmt->getColumnMeta($i);
  var_dump($metadata);
}

    ?>

当我执行代码时:,它显示

When I execute the code:, it displays

   array
  'native_type' => string 'LONG' (length=4)
  'pdo_type' => int 2
  'flags' => 
    array
      empty
  'table' => string 'friends' (length=7)
  'name' => string 'id' (length=2)
  'len' => int 11
  'precision' => int 0

array
  'native_type' => string 'VAR_STRING' (length=10)
  'pdo_type' => int 2
  'flags' => 
    array
      empty
  'table' => string 'friends' (length=7)
  'name' => string 'name' (length=4)
  'len' => int 60
  'precision' => int 0

到这里为止,它给出了正确的行数,但我需要将结果显示为它在我的数据库中的样子

Till here, it is giving the correct count of rows, but I need the result to display as it looks in the my database like

输出:

id name
1  Hebert
2  LG
3  Levins

如何获取所有字段,因为它就像使用元数据的数据库中的表一样.

How could I get all my fields as it is like a table in my database using metadata.

推荐答案

使用 columnCount.

$stmt = $db->query("SELECT * FROM friends");
$cnt_columns = $stmt->columnCount();
for($i = 0; $i < $cnt_columns; $i++) {
  $metadata = $stmt->getColumnMeta($i);
  var_dump($metadata);
}

顺便说一下,getColumnMeta实验性的.不推荐使用.为什么要使用它?

By the way, getColumnMeta is experimental. Not recommended to use. Why do you want to use it?

对于所需的输出,您不需要元数据.只需遍历结果:

For the desired output, you don't need metadata. Just loop through the results:

$sql = "SELECT * FROM friends";
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

// field names
if(count($result) > 0) {
   foreach($result[0] as $k => $v) {
     if(!is_int($k)) {
       echo $k . "\t";
     }
   }
}
echo PHP_EOL;

// data
foreach ($result as $row) {
    foreach($row as $k => $v) {
      if(!is_int($k)) {
        echo $row[$k] . "\t";
      }
    }
    echo PHP_EOL;
}

这篇关于PHP-PDO 从数据库中获取元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆