PDO使ってPostgreSqlに接続するには
【開発環境】
xampp 1.8.3
PHP 5.5.9
PostgreSQL 9.5.7
Eclipse 4.4
【PostgreSQL側の準備】
1)PostgreSQLを立ち上げる
C:\>psql -U postgres
psql (9.5.7)
"help" でヘルプを表示します
2)データベース「uriage」を作成
postgres=# create database uriage;
CREATE DATABASE
postgres=#
3)データベースの確認
postgres=# ¥l
参考までにユーザーを確認
postgres=# ¥du
4)データベースに接続する
postgres=# ¥connect uriage
データベース "uriage" にユーザ"postgres"として接続しました。
5)「shouhin」テーブルの作成
uriage=# create table shouhin(id integer,name text);
CREATE TABLE
uriage-# ¥dt
リレーションの一覧
スキーマ | 名前 | 型 | 所有者
----------+---------+----------+----------
public | shouhin | テーブル | postgres
(1 行)
6)データ入力
uriage=# insert into shouhin(id,name) values(1,'テレビ');
INSERT 0 1
uriage=# insert into shouhin(id,name) values(2,'DVDレコーダー');
INSERT 0 1
uriage=# insert into shouhin(id,name) values(3,'パソコン');
INSERT 0 1
uriage=# insert into shouhin(id,name) values(4,'携帯電話');
INSERT 0 1
uriage=# insert into shouhin(id,name) values(5,'プリンター');
INSERT 0 1
uriage=#
7)表示
uriage=# select * from shouhin;
id | name
----+---------------
1 | テレビ
2 | DVDレコーダー
3 | パソコン
4 | 携帯電話
5 | プリンター
(5 行)
8)アクセス権
uriage=# ¥z shouhin
アクセス権
スキーマ | 名前 | 型 | アクセス権 | Column privileges | Policies
----------+---------+----------+------------+-------------------+----------
public | shouhin | テーブル | | |
9)「pdotest2.php」サンプルを書いてみた
<html>
<head><title>PHP TEST</title></head>
<body>
<?php
function convert_enc($str){
$from_enc = 'utf8';
$to_enc = 'utf8';
return mb_convert_encoding($str, $to_enc, $from_enc);
}
$dsn = 'pgsql:dbname=uriage host=localhost port=5432';
$user = 'postgres';
$password = '●●●●';
try{
$dbh = new PDO($dsn, $user, $password);
print('接続に成功しました。');
$sql = 'select * from shouhin';
foreach ($dbh->query($sql) as $row) {
print(convert_enc($row['id']));
print(convert_enc($row['name']).'');
}
}catch (PDOException $e){
print('Error:'.$e->getMessage());
die();
}
$dbh = null;
?>
</body>
</html>
10)表示