Category: PHP

QuickFormのValidateにコールバックを適応する

addRuleするときに下記のようにコーディングするとvalidate()を呼び出すときに、
“addFormRule”で指定した同じクラスのvalidateCallBackが最後に起動される。

class qf_form extends HTML_QuickForm{
    function buildRule(){
        //コールバック関数
        $this->addFormRule(array($this, 'validateCallBack'));
   }
   function validateCallBack( $from_data ){
    $errors = array();
       print_r( $form_data );
      return $errors;
   }
}

参考記事
http://pear.plus-server.net/package.html.html-quickform.html-quickform.addformrule.html

Docomo携帯にCSSを適応するときの注意点

出力するときのHTMLコードがXHTMLの時には、下記のコードが必要になります。

 header('Content-Type: application/xhtml+xml');

ただし、同HTMLコードをPCで確認するとき上記の記述があると、FireFoxはクラッシュします。また、Chormeでも正常に表示できない場合があります。
上記のコードはあくまでもDocomoのみ出力するように制御する必要があります。

PHPを書こう!

前回はインストールして終わりました。今回はPHPの簡単なプログラムを書いてみましょう!

PHPはテキスト処理が得意な言語です。そして、PHPの初期はC言語とPerlをかけ合わせてものになっています。なので、C言語を勉強した人も、Perlを勉強した人も、あまり抵抗なくPHPを描くことができると思います。(C言語から入ってきた人は変数宣言が無いということに気持ち悪いと思う人がおおいでしょうけども)

適当なフォルダに、”Hello.php”というテキストファイルを作って見ましょう。Hello.phpは、下記のような内容にします。

<?php
 echo ("Hallow!!");
?>

Hello.phpファイルに上記の内容をタイプして保存します。
そして、コンソールを立ち上げて、ファイルを作成したフォルダに移動します。
そこで、Hello.phpを起動してみましょう。

私の場合、Eドライブのe:\home\php_baseという場所にファイルを作成しましたので、コンソールでは下記のようにコマンドを発行します。

> e: [enter]
> dir e:\home\php_base [enter]
> php Hello.php [enter]
Hello

3行目を入力すると、4行目が自動的に出力されます。この4行目がPHPの実行結果になるわけです。
Hello.phpは、この”Hello”を出力するためのPHPのプログラムだったのです!!

とりあえず、これでPHPのプログラムを書き、動作させることに成功しました。

おめでとうございます。

今回はここまでです。

PHPを手に入れろ!

Webアプリケーションを作るプログラム言語は、Perl,PHP,Ruby,C,C++など様々な言語がある。一般的にはPHPですが、少し昔の主流はPerlでした。とにかく高速化が求められるニーズでは、C,C++が使用されています。
Rubyは、ビジネス業界ではあまり聞きません。たま~に、お客様が知っているからという理由で採用されることもありますが…

Webアプリケーションのほとんどは、サーバー上で動作するため、開発環境はUnix系のOS上で行われることになります。なので、Webアプリケーションを作成する場合Unixの知識も必要になってきます。

さて、とにかくPHPをインストールしてみましょう。最近では、Windows用のPHPも配布されているので、Windows環境でも容易にPHPを導入することができます。

PHPの入手は、下記のURLから行うことができます。とりあえずは、最新のバージョンのWindowsインストーラをダウンロードするといいでしょう。

http://php.net/downloads.php

ダウンロードと、インストールが終わったらWindowsのコンソール(コマンドプロンプト)を立ち上げてPHPが起動するかをやってみましょう。

コンソールを立ち上げて、
> php -v [Enter]

と入力すると。PHPのバージョンば出力され、PHPは終了します。
渡しの環境の場合は、このように出力されました。

C:\Users\AllUser>php -v
PHP 5.3.2 (cli) (built: Mar 3 2010 20:36:54)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

上記の出力結果から、PHPのバージョンは5.3.2がインストールされていることが分かります。
とにかく、これでPHPがインストールし、動作することが確認できました。

お疲れ様です。今回はここまで。

PDOを利用したDBアクセスクラス(自作ですけども)


// PDOを利用したデータベースクラス
class pdbo{
	private static	$pdo;
	private static	$conf;

	private function __construct(){
	}

	public function Factory( $table ){
		if( is_null( pdbo::$conf ) ){
			$tmp = new Config( CONF_PATH.'db.ini' );
			$tmp = $tmp->Get();
			pdbo::$conf = $tmp['DataBase'];
		}
		if( is_null( pdbo::$pdo ) ){
			try{
				pdbo::$pdo = new PDO( pdbo::$conf['dns'],
					pdbo::$conf['user'], pdbo::$conf['password'] );
			} catch( PDOException $e ){
				echo $e->GetMessage();
				throw new Exception( $e->getMessage() );
			}
		}
		return new dbo( pdbo::$pdo, '', $table );
	}

}

class dbo{
	private $dbo;
	private $db_name;
	private $table_name;
	private $fileds;
	private $error_message;
	private $query_log = array();

	public function __construct( $pdbo, $db, $table ){
		$this->dbo		= $pdbo;
		$this->db_name	= $db;
		$this->table_name	= $table;

		//テーブル情報取得
		try{
			$ret = $pdbo->query( 'DESCRIBE '.$table );
		} catch( PDOException $e ){
			$this->error_message = $e->getMessage();
			throw new Exception( $this->error_message );
		}
		$tmp = $ret->fetchAll( PDO::FETCH_ASSOC );
		foreach( $tmp as $node ){
			$type = $this->getType( $node['Type'] );
			$this->fileds[$node['Field']]['type']= $type['type'];
			$this->fileds[$node['Field']]['size']= $type['size'];
			$this->fileds[$node['Field']]['option']= $type['option'];
			$this->fileds[$node['Field']]['null']= $node['Null'];
			$this->fileds[$node['Field']]['key']	= $node['Key'];
		}
	}

	public function DumpQuerys(){
		print_r( $this->query_log );
	}
	/**
	 * 一行だけレコードを取得する
	 *  $flagがtrueの時、条件配列にプライマリキーが存在しない場合エラーに
	 *  なります
	 * @param	array	$condition	条件配列
	 * @param	bool	$flag		プライマリキー存在チェック
	 */
	public function getOnce( $condition, $flag = true ){
		$table	= $this->table_name;
		$dbo	=& $this->dbo;
		if( $flag ){
			//プライマリーキーの存在チェック
			$primary = $this->getPrimary();
			$keys = array_keys( $condition );
			foreach( $primary as $name  ){
				if( !in_array( $name, $keys ) ){
					throw new Exception('プライマリーキーが設定されていません');
				}
			}
		}

		//検索条件生成
		$ret = null;
		try{
			$where = $this->makeWhere( $condition );

			$sql = "SELECT * FROM {$table}";
			if( strlen( $where ) > 0 ) $sql .= $where;
			$this->query_log[] = $sql;
			$ret = $dbo->query( $sql );

		} catch( PDOException $e ){
			$this->error_message = $e->getMessage();
			throw new Exception( $this->error_message );
		}

		//エラー処理
		if( $ret === false )  throw new Exception( "query error: {$sql}");

		//複数行検出
		if( $ret->rowCount() != 1 ) return false;

		return $ret->fetch(PDO::FETCH_ASSOC);
	}

	public function getAll($condition = array(), $order = array()){
		$table	= $this->table_name;
		$dbo	=& $this->dbo;

		//検索条件生成
		$ret = null;
		try{
			$where = $this->makeWhere( $condition );
			$_order = $this->makeOrder( $order );

			$sql = "SELECT * FROM {$table}";
			$sql .= $where;
			$sql .= $_order;
			$this->query_log[] = $sql;
			$ret = $dbo->query( $sql );

		} catch( PDOException $e ){
			$this->error_message = $e->getMessage();
			throw new Exception( $this->error_message );
		}

		//エラー処理
		if( $ret === false )  throw new Exception( "query error: {$sql}");

		return $ret->fetchAll(PDO::FETCH_ASSOC);
	}

	public function getPaging( $condition = array(), $order, &$page ){
		$table	= $this->table_name;
		$dbo	=& $this->dbo;

		//検索条件生成
		$res = null;
		try{
			$where = $this->makeWhere( $condition );
			$_order = $this->makeOrder( $order );

			$sql = "SELECT * FROM {$table}";
			$sql .= $where;
			$sql .= $_order;
			$this->query_log[] = $sql;
			$res = $dbo->query( $sql );

		} catch( PDOException $e ){
			$this->error_message = $e->getMessage();
			throw new Exception( $this->error_message );
		}

		//エラー処理
		if( $res === false )  throw new Exception( "query error: {$sql}");

		$page['rowCount'] = $res->rowCount();
		$page['pageMax'] = ceil( $page['rowCount'] / $page['limit'] );
		$page['start']	= ($page['now'] - 1 )* $page['limit'] + 1;
		$page['end']	= $page['now'] * $page['limit'];
		if( $page['end'] > $page['rowCount'] ) $page['end'] = $page['rowCount'];
		$ret = array();
		for( $n = $page['start']; $n <= $page['end']; $n ++ ){
			$ret[] = $res->fetch( PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, $n );
		}
		return $ret;
	}

	/**
	 * 唯一のレコード更新
	 */
	public function updateOnce( $data ){
		$table	= $this->table_name;
		$dbo	=& $this->dbo;
		$fileds =& $this->fileds;

		//更新データ
		$up_data = array();
		//条件データ
		$condition = array();
		foreach( $data as $name => $val ){
			list( $nm ) = $this->getFiledName( $name );
			if( $fileds[$nm]['key'] == 'PRI' ){
				$condition[$name] = $val;
			} else {
				$up_data[$name] = $val;
			}
		}

		return $this->update( $up_data, $condition );
	}

	/**
	 * 複数更新
	 */
	public function update( $data, $condition ){
		$table	= $this->table_name;
		$dbo	=& $this->dbo;
		$fileds =& $this->fileds;
		$node = array();
		try{
			$where = $this->makeWhere( $condition );
			foreach( $data as $name => $val){
				$val = addslashes($val);
				//日付時にクォートをつける
				if( $this->isDate($fileds[$name]['type']) ) {
					if( $val == $val * 1 ){
						$val = "'".date( 'Y-m-d H:i:s', $val )."'";
					}
				}
				//文字型にシングルクォートをつける
				if( $this->isString($fileds[$name]['type']) ) {
					$val = "'{$val}'";
				}
				$node[] = "{$name} = {$val}";
		   	}
			$sql = "UPDATE {$table} SET ".implode( ' , ', $node )." {$where}";
			$this->query_log[] = $sql;
			$dbo->query( $sql );
		} catch( Exception $e){
			echo $e->getMessage();
			return false;
		}
		return true;
	}

	/**
	 * 一行だけレコードを取得する
	 *  $flagがtrueの時、条件配列にプライマリキーが存在しない場合エラーに
	 *  なります
	 * @param	array	$data		登録情報
	 * @param	bool	$flag		プライマリキー存在チェック
	 */
	public function insert( $data, $flag = true ){
		if( count( $data ) == 0 ) return false;
		//インサートチェック
		if( ($name = dbo::existsFiled($data,$this->getNotNull())) !== true ){
			throw new Exception(
				"{$name}はnot nullのフィールドですが、存在していませんでした。"
		   	);
		}
		$fileds =& $this->fileds;
		//文字列次処理
		foreach( $data as $name => $val ){
			//文字列時にクォートをつける
			if( $this->isString($fileds[$name]['type']) ){
				$val = "'".addslashes($val)."'";
			}
			//日付時にクォートをつける
			if( $this->isDate($fileds[$name]['type']) ) {
				if( is_int( $val ) ){
					$val = date( 'Y-m-d H:i:s', $val );
				}
				$val = "'".addslashes($val)."'";
			}
			$data[$name] = $val;
		}

		$tmp = array();
		foreach( $data as $name => $val ) $tmp[] = "{$val}";

		$sql = "INSERT INTO {$this->table_name} ( ".
			implode( ' , ', array_keys($data) )." ) VALUES ( ";
		$sql .= implode( ', ', $tmp )." ); ";
		try{
			$this->query_log[] = $sql;
			$ret = $this->dbo->query( $sql );
		} catch( PDOException $e ) {
			throw new Exception( 'Insert Error:'.$e->getMessage() );
		}
		if( $ret === false ){
			throw new Exception( 'Insert Error: '.$sql );
		}
		return true;
	}

	public function delete( $condition = array() ){
	}

	/**
	 * 条件削除
	 */
	public function deleteSearch( $condition ){
		if( count( $condition ) == 0 ) return false;

		$sql = "DELETE FROM {$this->table_name} ".$this->makeWhere($condition);

		try{
			$this->query_log[] = $sql;
			$ret = $this->dbo->query( $sql );
		} catch( PDOException $e ) {
			throw new Exception( 'Insert Error:'.$e->getMessage() );
		}
		return true;
	}

	/**
	 * Where句の生成
	 */
	private function makeWhere( $condition ){
		if( count( $condition ) == 0 ) return '';
		$fileds = $this->fileds;
		$where = array();
		foreach( $condition as $key => $val ){
			$val = addslashes( $val );
			$option = '';
			//オプション検出
			if( strpos( $key, ':' )  !== false ){
				//オプション取得
				$tmp = $key;
				list( $key, $option ) = explode( ':', $tmp );

				//テーブルにカラムが存在するか
				if( !isset( $fileds[$key] ) ){
					throw new Exception(
						"{$key}は{$this->table_name}に存在しないカラムです"
				   	);
				}

				//文字列 日付型 の場合の処理
				if( $this->isString( $fileds[$key]['type'] ) ||
					$this->isDate( $fileds[$key]['type'] )
				) {
					$val = "'{$val}'";
				}

				switch( $option ){
					case 'not':
						$where[] = "{$key} <> {$val}";
						break;

					case 'begin':
						$where[] = "{$key} >= {$val}";
						break;
					case 'quit':
						$where[] = "{$key} <= {$val}";
						break;

					case 'start':
						$where[] = "{$key} > {$val}";
						break;

					case 'end':
						$where[] = "{$key} < {$val}";
						break;

					case '--':
						$where[] = "{$key} {$val}";
						break;

					case 'like':
						$where[] = "{$key} LIKE {$val}";
						break;

					case 'eq':
						$where[] = "{$key} = {$val}";
						break;

					case 'neq':
						$where[] = "{$key} = {$val}";
						break;

					default:
						throw  new Exception( 'makeWhere error: '.
							'指定されないオプションを検出しました'
					   	);
				}
			} else {
				//オプションが無いとき

				//テーブルにカラムが存在するか
				if( !isset( $this->fileds[$key] ) ){
					throw new Exception(
						"{$key}は{$this->table_name}に存在しないカラムです"
				   	);
				}

				if( $this->isString($fileds[$key]['type'] ) ) {
					$where[] = "{$key} LIKE '%{$val}%'";
				} else {
					$where[] = "{$key} = {$val}";
				}
			}
		}
		return " WHERE ".implode( ' AND ', $where );
	}

	/**
	 *
	 */
	protected function makeOrder( $order ){
		if( count( $order ) == 0 ) return '';

		$ret = array();
		$fileds = $this->fileds;
		$kyes = array_keys( $order );
		//テーブルにカラムが存在するか
		foreach( $order as $name => $val ){
			if( !isset( $fileds[$name] ) ){
				throw new Exception(
					"{$key}は{$this->table_name}に存在しないカラムです"
		   		);
			}
			$ret[] = "{$name} {$val}";
		}
		return " ORDER BY ".implode( " , ", $ret );
	}

	/**
	 * 文字型かを判別する
	 */
	protected function isString( $type ){
		switch( strtolower($type) ){
			case 'char':
			case 'varchar':
			case 'text':
				return true;
		}
		return false;
	}

	/**
	 * 日付型かを判別する
	 */
	protected function isDate( $type ){
		switch( strtolower($type) ){
			case 'date':
			case 'datetime':
			case 'timestamp':
				return true;
		}
		return false;
	}

	/**
	 * Mysqlのカラムタイプから型とサイズ、オプション属性を切り離す
	 */
	private function getType( $type ){
		$ret = array(
			'size'	=> '',
			'type'	=> '',
			'option'=> '',
		);
		$st	= 0;
		$end= 0;
		$st = strpos( $type, '(' );
		if( $st === false ){
			$ret['type'] = $type;
			return $ret;
		}
		$ret['type'] = substr( $type, 0, $st );
		$end = strpos( $type, ')' );
		$ret['size'] = substr( $type, $st+1, $end-$st-1 );
		$tmp = explode( ' ', $type );
		if( count( $tmp ) > 1 ) $ret['option'] = $tmp[1];
		return $ret;
	}

	/**
	 * プライマリーキー配列の取得
	 */
	private function getPrimary(){
		$ret = array();
		foreach( $this->fileds as $name => $node ){
			if( $node['key'] == 'PRI' ){
				$ret[] = $name;
			}
		}
		return $ret;
	}

	private function getNotNull(){
		$ret = array();
		foreach( $this->fileds as $name => $node ){
			if( $node['null'] == 'No' ){
				$ret[] = $name;
			}
		}
		return $ret;
	}

	/**
	 * $list配列内のフィールドが$filedsに含まれているかチェックする
	 */
	private function existsFiled( $fileds, $list ){
		$keys = array_keys( $fileds );
		foreach( $list as $name ){
			if( !in_array( $name, $keys ) ) return $name;
		}
		return true;
	}

	private function getFiledName( $name ){
		if( strpos(  $name, ':' )  === false ) return array( $name, '' );
		return explode( ':', $name );
	}
}

WordPress Themes