LoginSignup
2

More than 5 years have passed since last update.

テーブルのカラム名をプログラム中に取得したい。

Last updated at Posted at 2016-09-22

PHP5.6
SQL文を動的に組み立てたい時などに。

class Db
{
  // ・・・

  private $pdo; // PDOインスタンス必要

  public function getColumnNames($table_name)
  {
    $sql = "SELECT * FROM {$table_name} LIMIT 0";
    $stmt = $this->pdo->query($sql);
    for ($i = 0; $i < $stmt->columnCount(); $i++):
      $column_names[] = $stmt->getColumnMeta($i)['name'];
    endfor;

    return $column_names;
  }

  // ・・・
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2