ちょっと、PHPからPostgresqlのテーブルへアクセスしたいなって時に、使い回し出来そうなサンプルプログラム。
<?php
/**
* ConnnectDBクラス
*/
class ConnnectDB {
// データベース設定
private $server = "localhost";
private $user = "username";
private $password = "password";
private $dbname = "database";
private $count = 0;
/**
* コンストラクタ
*
* @return void
*/
function ConnnectDB()
{
$cnstr="host=".$this->server
." port=5432 dbname=".$this->dbname
." user=".$this->user
." password=".$this->password;
pg_connect($cnstr);
}
/**
* テーブルからレコード取得
*
* @return objects
*/
function getRecord()
{
if(!($result = pg_exec("select * from table")) ){
return "-1";
}
$this->count = pg_numrows($result);
return $this->_convertObject($result, $this->count);
}
/**
* レコードの件数取得
*
* @return レコード件数
*/
function getCount() {
return $this->count;
}
/**
* update
*
* @param $updates アップデートさせたいカラム名の配列
* @return bool
*/
function update($updates)
{
$sets = array();
foreach ($updates as $key=>$value) {
$value = $this->_escape($value);
$tmp = "$key = '$value'";
array_push($sets, $tmp);
}
$set = join(",", $sets);
$sql = "update table set $set";
// echo $sql;
$result = pg_exec($sql);
return $result;
}
/**
* パラメータのエスケープ
*
* @param $str
* @return エスケープされたデータ
*/
function _escape($str)
{
$escaped = pg_escape_string($str);
return $escaped;
}
/**
* 結果セットをオブジェクトの配列で返却
*
* @param &$result
* @return objects
*/
function _convertObject($result, $ct)
{
$ret = array();
for ($i = 0; $i < $ct; $i++) {
$obj = pg_fetch_array($result,$i);
array_push($ret, $obj);
}
return $ret;
}
}
?>
updateメソッドには、where句で更新対象レコードを絞れるようにしておきたい。このクラスの使い方は、こんな感じで。insert文は今回は作成せず・・・(;^_^A
<?php
require_once 'ConnnectDB.php';
$db = new ConnnectDB();
// テーブルデータ取得
$record = $db->getRecord();
echo "<pre>";
print_r($record);
echo "</pre>";
// テーブルデータの更新
$update["title"] = "test title";
$update["timerecorder"] = date("Y-m-d H:i:s");
$result = $db->update($update);
?>
コメント
コメントを投稿