1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PDOでデータベースに特定のテーブルがあるか確認する方法

Last updated at Posted at 2021-02-05

環境

他のDBや言語とかでも考え方だけ真似れば使えるはず

  • Windows
  • PHP
  • PostgreSQL

コード

table_check.php
try{
	  // データベースに接続
	  $set = new PDO('pgsql:host=****; dbname=****;', '***', '****');	
	  echo "接続に成功しました!!<br/><br/>";

	  //テーブルの有無を判断
      //@error_401 さんのコメントより
	  $sql = "SELECT 1 FROM information_schema.tables WHERE table_name = 'abc'";
      $query = $set->query($sql);
      $data = $query->fetchAll(PDO::FETCH_ASSOC);
	  if($data['0']['?column?'] == 1){
	  	echo "テーブルが存在しました。";
	  }

	  //エラー表示
	  }catch(PDOException $error) {
?>

<div style="color: red"><?php print($error->getMessage()); ?></div>

<?php
	}
	// データベースとの接続を切断
	$set = null;
?>

解説

$sql = "SELECT 1 FROM information_schema.tables WHERE table_name = 'abc'"; で、存在しているかどうかを知りたいテーブルが存在しているかどうかを取得できる。
取得の際、オブジェクトになるため、 **$data = $query->fetchAll(PDO::FETCH_ASSOC);**で配列に変換する。
そうすると、以下のような配列ができる。

array(1) { [0]=> array(1) { ["?column?"]=> int(1) } }

存在していれば**['?column?']の値が1になる。
以上のコードを使って、テーブルの存在を確かめ、
if($data['0']['?column?'] == 1)**でテーブルが存在していた際の処理を記入していく。

1
1
3

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?