2010年5月5日水曜日

CentOS で LAPP その1 インストール

CentOS で、PHP PostgreSQL の開発するための手順を記述する。その 1 では、最低限 PHP と PostgreSQL が連携し、動作するまでの手順を記述する。

root 権限でコンソールを起動する。

PHP のインストール
# yum -y install php php-gd php-postgres php-mbstring php-pgsql php-pear
# PHP -v
PHPのバージョン情報が表示されれば OK 。

PostgreSQL がインストールされているか確認する。
# rpm -qa |grep postgres
postgresql、postgresql-server、postgresql-libs がインストールされていれば、次の手順(PostgreSQL をインストールする。)は行わない。

PostgreSQL をインストールする。今回は確認したときに postgresql、postgresql-server がインストールされていれなかった場合の例 。
# yum -y install postgresql postgresql-server
PostgreSQL のポートを開き、PHP からアクセス出来るようにする。
# vim /var/lib/pgsql/data/postgresql.conf 
listen_addresses = 'localhost' のコメントアウトを外す。

SELinux の設定。PHP から PostgreSQL にアクセスできるようにする。
# getsebool -a | grep db
httpd_can_network_connect_db -->; off
httpd_can_network_connect_db が off なら、次のコマンドを実行する。
# setsebool -P httpd_can_network_connect_db on
httpd_can_network_connect_db が on になったのを確認する。
# getsebool -a | grep db
httpd_can_network_connect_db -->; on
Apach を起動する。
# /etc/init.d/httpd start
Apache の起動を確認する。ブラウザに http://localhost/と入力する。Apache2 Test Page が表示されれば OK 。

データベースを操作する毎に su するのは面倒なので、postgres 以外のユーザーでもデータベースを操作できるようにする。また、PHP から PostgreSQL に接続できるようにする。
# vim /var/lib/pgsql/data/pg_hba.conf
local all all ident sameuser
host all all 127.0.0.1/32 sameuser
の2箇所の ident sameuser を trust に変える。

PostgreSQL を起動する。
# /etc/init.d/postgresql start
テスト用のデータベースを作成する。
# su - postgres
-bash-3.2$ createdb testdb
-bash-3.2$ psql testdb
testdb=# create table testtable (col1 int,col2 int);
testdb=# insert into testtable (col1,col2) values (123,456);
testdb=# insert into testtable (col1,col2) values (567,789);
testdb=# \q
-bash-3.2$ exit
テスト用の PHP を作成する。
# vi /var/www/html/dbtest.php
下記の内容で作成。
<?php
 define('DB_CONNECT'
  ,'host=localhost
  port=5432
  dbname=testdb
  user=postgres
  password=pass');
 $con = pg_connect(DB_CONNECT) or die('pg_connect is error');
 $sql = 'SELECT col1,col2 FROM testtable;';
 $rs = pg_query($con ,$sql) or die ('pg_query is error');
 while($row = pg_fetch_array($rs)){
   echo $row['col1'] . ' ' .  $row['col2'] . '';
 }
 pg_close($con);
?>
ブラウザに http://localhost/dbtest.php と入力する。123 456 ... が表示されれば OK 。

動作環境 CentOS 5.4

参考

Lets' postgres - CentOS で PostgreSQL を使ってみよう!
http://lets.postgresql.jp/documents/tutorial/centos/

0 件のコメント:

コメントを投稿