검색결과 리스트
PHP/PHP5 클래스에 해당되는 글 3건
- 2012.05.10 php5 simple xml을 이용한 xml 파싱 클래스 11
- 2012.04.03 PHP5 Exception 예외처리 사용 방법과 그 종류
- 2012.03.20 php5 mysqli 디비 접속 클래스 프로그램 및 사용법
글
php5 simple xml을 이용한 xml 파싱 클래스
PHP/PHP5 클래스
2012. 5. 10. 13:57
php5 에서는 simpleXML 이라는 강력하고도 좋은 xml 클래스를 제공합니다.
이 클래스를 활용해서 보다 내가 원하는 형태로 데이타를 찾고
변환 할 수 있도록 클래스를 만듭니다.
#@ xml 파일 내용 /====================================
< ?xml version='1.0' encoding='UTF-8'? > < main> < head> < title>타이틀< /title> < summary>써머리라고 하징< /summary> < /head> < navigation id="3000"> < margin>30< /margin> < item title="메뉴1" image_off="" image_on="" /> < item title="메뉴2" image_off="" image_on="" /> < item title="메뉴3" image_off="" image_on="" /> < item title="메뉴4" image_off="" image_on="" /> < item title="메뉴5" image_off="" image_on="" /> < item title="메뉴6" image_off="" image_on="" /> < /navigation> < background> < image>< /image> < color>< /color> < /background> < /main>
#@ php 클래스 선언 ----
< ?php $sx =new XmlSimple($path.'/modules/main.xml');
#@ xml : head 데이타만 추출하기/==========================
$result=$sx->query('head'); $args1=$sx->fetch($result); print_r($args1); // 결과 Array ( [0] => Array ( [title] => 타이틀 [summary] => 써머리라고 하징 ) )
#@ 네비게이션 메뉴 만 추출하기 /============================
$result=$sx->query('navigation'); $args1=$sx->fetch($result); print_r($args1); // 결과 Array ( [0] => Array ( [attr] => Array ( [id] => 3000 ) [margin] => 30 [item] => Array ( [0] => Array ( [attr] => Array ( [title] => 메뉴1 [image_off] => [image_on] => ) ) [1] => Array ( [attr] => Array ( [title] => 메뉴2 [image_off] => [image_on] => ) ) [2] => Array ( [attr] => Array ( [title] => 메뉴3 [image_off] => [image_on] => ) ) [3] => Array ( [attr] => Array ( [title] => 메뉴4 [image_off] => [image_on] => ) ) [4] => Array ( [attr] => Array ( [title] => 메뉴5 [image_off] => [image_on] => ) ) [5] => Array ( [attr] => Array ( [title] => 메뉴6 [image_off] => [image_on] => ) ) ) ) )
#@ 네비게이션 메뉴 중 item 값만 추출하기 /==================================
$result=$sx->query('navigation/item'); $args1=$sx->fetch($result); print_r($args1); // 결과 Array ( [0] => Array ( [attr] => Array ( [title] => 메뉴1 [image_off] => [image_on] => ) ) [1] => Array ( [attr] => Array ( [title] => 메뉴2 [image_off] => [image_on] => ) ) [2] => Array ( [attr] => Array ( [title] => 메뉴3 [image_off] => [image_on] => ) ) [3] => Array ( [attr] => Array ( [title] => 메뉴4 [image_off] => [image_on] => ) ) [4] => Array ( [attr] => Array ( [title] => 메뉴5 [image_off] => [image_on] => ) ) [5] => Array ( [attr] => Array ( [title] => 메뉴6 [image_off] => [image_on] => ) ) ) ? >
#@ simple xml 를 이용해 데이타 배열로 리턴해 주는 클래스 소스 /==============================
< ?php class XmlSimple { public $xml_obj; private $num_rows = 0; # query 엘리멘트 갯수 #@ void # xpath = xml 파일 경로 public function __construct($xpath){ if(!self::isExists($xpath)) throw new ErrorException('파일이 없어 어데간겨 잘 찾아봐',__LINE__); # 데이타 가져오기 if(!$xml_data = file_get_contents($xpath)) throw new ErrorException('No data',__LINE__); # simple xml $this->xml_obj = new SimpleXMLElement($xml_data); } #@ return xml array # navigation/item public function query($query){ $result=$this->xml_obj->xpath($query); $this->num_rows =count($result); return $result; } #@return array public function fetch($result) { $loop =array(); for($i=0; $i<$this->num_rows; $i++) { // attributes만 있을 수 있음 $attr_count=count($result[$i]->attributes()); if($attr_count>0) { $loop2=&$loop[$i]['attr']; foreach($result[$i]->attributes() as $k2=>$kv){ $loop2[$k2]=strval($kv); } } // child if(count($result[$i])){ foreach($result[$i] as $k=>$v) { // child -> attributes $attr_count=count($v->attributes()); if($attr_count>0) { $loop3=&$loop[$i][$k][]['attr']; foreach($v->attributes() as $k3=>$k3v){ $loop3[$k3]=strval($k3v); } }else{ $loop[$i][$k]=strval($v); } } } } return $loop; } #@ return public function __get($propertyName){ if(property_exists(__CLASS__,$propertyName)){ return $this->{$propertyName}; } } # 로컬 파일인지 체크 protected function isExists($filename){ if(!file_exists($filename)) return false; return true; } } ? >
'PHP > PHP5 클래스' 카테고리의 다른 글
PHP5 Exception 예외처리 사용 방법과 그 종류 (0) | 2012.04.03 |
---|---|
php5 mysqli 디비 접속 클래스 프로그램 및 사용법 (0) | 2012.03.20 |
설정
트랙백
댓글
글
PHP5 Exception 예외처리 사용 방법과 그 종류
PHP/PHP5 클래스
2012. 4. 3. 22:18
PHP5 Exception 사용 방법과 그 종류
BadFunctionCallException BadMethodCallException DomainException InvalidArgumentException LengthException LogicException OutOfBoundsException OutOfRangeException OverflowException RangeException RuntimeException UnderflowException UnexpectedValueException
@ Exception 종류 클래스 2
Exception ErrorException
@ 가장 많이 쓰는 Exception 클래스 소스
Exception { /* 프로퍼티 */ protected string $Exception->message ; protected int $code ; protected string $file ; protected int $line ; /* 메소드 */ public Exception::__construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] ) final public string Exception::getMessage ( void ) final public Exception Exception::getPrevious ( void ) final public mixed Exception::getCode ( void ) final public string Exception::getFile ( void ) final public int Exception::getLine ( void ) final public array Exception::getTrace ( void ) final public string Exception::getTraceAsString ( void ) public string Exception::__toString ( void ) final private void Exception::__clone ( void ) }
@ 사용법
/*방법 1*/ try { echo inverse(5) . "\n"; echo inverse(0) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } /*방법 2*/ function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } else return 1/$x; } /* 방법 3 */ class Test{ public init($s){ if(!empty($s)) throw new Exception('Division by zero.'); } }
'PHP > PHP5 클래스' 카테고리의 다른 글
php5 simple xml을 이용한 xml 파싱 클래스 (11) | 2012.05.10 |
---|---|
php5 mysqli 디비 접속 클래스 프로그램 및 사용법 (0) | 2012.03.20 |
설정
트랙백
댓글
글
php5 mysqli 디비 접속 클래스 프로그램 및 사용법
PHP/PHP5 클래스
2012. 3. 20. 20:55
웹스크립트언어의 최강자 PHP 프로그램입니다.
PHP를 사용하려면 반드시 알아야 할것이 디비접속을 하여 그 데이타를 추출할 줄 알아야
좋은 프로그램을 만들 수 있지요
PHP5 부터는 많음 클래스 들을 제공하는데
그 중에 하나가 mysqli 라는 클래스 입니다.
이 클래스 mysqli 를 그대로 상속받아
좀더 사용하기 쉽도록 mysqli 관련 클래스를 만들드록 하겠습니다.
하지만, 모든 언어가 그렇듯이
PHP도 반드시 mysql 에만 접속 해서 사용하라는 법이 없습니다.
다양한 데이타베이스에 접속해서 사용을 할 수 있죠
그렇지만 php 코딩은 갖습니다.
단 디비만 바뀌는 거죠 이렇게 디비만 바뀌면 되는데
디비를 접속하고 쿼리 날리고 저장하고 하는 일들에 대해
프로그램을 수정해야 한다면 정말 일이 많고 스트레스가 상승하게 됩니다.
이러한 불편한 작업들을 하지 않기 위해서
하나의 interface를 정의해 놓고
다른 여러 프로그래머들이 데이타 베이스 프로그램을 작성 할때
동일한 메소드들을 정의하고 사용하도록 규칙을 정합니다.
가장 많이 사용하는
query, insert, modify, delete 등이죠
최소한의 것을 정의해서 사용하는 겁니다.
더 많은 것들을 정의 할 수 있지만
우선 위의 것들을 정의한 interface 를 만들고 mysqli를 상속 받아
보다 사용하기 편리한 데이타베이스 클래스 파일을 만들어 보겠습니다.
@ interface : DbSwitch 클래스를 만들겠습니다.
@ 디비 접속 정보를 미리 설정해 놓겠습니다.
@ DbMySqli : [클래스1개] mysqli, [인터페이서 2개] DbSwitch, ArrayAccess 를 상속 받아 구현을 합니다.
여기서 부터는
member 테이블이 있다고 가정하고
uid : 회원고유번호 userid : 아이디 name : 이름 passwd : 비밀번호 email : 이메일 정보 hp : 휴대폰
1. 데이타 입력
2. 데이타 쿼리
3. 데이타 수정
4. 데이타 삭제 예문을 보겠습니다.
1. insert 디비 저장 /-------------------
2. query 디비 쿼리 /---------------------------
3. update 디비 정보 수정 /----------------------------------
4. delete 디비 삭제 /----------------------------------------
PHP를 사용하려면 반드시 알아야 할것이 디비접속을 하여 그 데이타를 추출할 줄 알아야
좋은 프로그램을 만들 수 있지요
PHP5 부터는 많음 클래스 들을 제공하는데
그 중에 하나가 mysqli 라는 클래스 입니다.
이 클래스 mysqli 를 그대로 상속받아
좀더 사용하기 쉽도록 mysqli 관련 클래스를 만들드록 하겠습니다.
하지만, 모든 언어가 그렇듯이
PHP도 반드시 mysql 에만 접속 해서 사용하라는 법이 없습니다.
다양한 데이타베이스에 접속해서 사용을 할 수 있죠
그렇지만 php 코딩은 갖습니다.
단 디비만 바뀌는 거죠 이렇게 디비만 바뀌면 되는데
디비를 접속하고 쿼리 날리고 저장하고 하는 일들에 대해
프로그램을 수정해야 한다면 정말 일이 많고 스트레스가 상승하게 됩니다.
이러한 불편한 작업들을 하지 않기 위해서
하나의 interface를 정의해 놓고
다른 여러 프로그래머들이 데이타 베이스 프로그램을 작성 할때
동일한 메소드들을 정의하고 사용하도록 규칙을 정합니다.
가장 많이 사용하는
query, insert, modify, delete 등이죠
최소한의 것을 정의해서 사용하는 겁니다.
더 많은 것들을 정의 할 수 있지만
우선 위의 것들을 정의한 interface 를 만들고 mysqli를 상속 받아
보다 사용하기 편리한 데이타베이스 클래스 파일을 만들어 보겠습니다.
@ interface : DbSwitch 클래스를 만들겠습니다.
< ?php # purpose : 각종 SQL 관련 디비를 통일성있게 작성할 수 있도록 틀을 제공 interface DbSwitch { public function query($query); # 쿼리 public function insert($table); # 저장 public function update($table,$where); # 수정 public function delete($table,$where); # 삭제 public function bindParams($query,$args=array()); #쿼리 문자 바인드효과 } ? >
@ 디비 접속 정보를 미리 설정해 놓겠습니다.
< ?php define('_DB_HOST_','localhost'); #접속 경로 define('_DB_USER_','apmsoft'); #접속 아이디 define('_DB_PASSWD_','password'); #접속 비밀번호 define('_DB_NAME_','apmsoft_db'); #접속 데이타베이스 명 ? >
@ DbMySqli : [클래스1개] mysqli, [인터페이서 2개] DbSwitch, ArrayAccess 를 상속 받아 구현을 합니다.
< ?php # Parent : MySqli # Parent : DBSwitch # purpose : mysqli을 활용해 확장한다 class DbMySqli extends mysqli implements DbSwitch,ArrayAccess { private $params = array(); # dsn : host:dbname = localhost:dbname public function __construct($dsn='',$user='',$passwd='',$chrset='utf8') { # 데이타베이스 접속 if(!empty($dsn)){ $dsn_args = explode(':',$dsn); parent::__construct($dsn_args[0],$user,$passwd,$dsn_args[1]); }else{//config.inc.php --> config.db.php parent::__construct(_DB_HOST_,_DB_USER_,_DB_PASSWD_,_DB_NAME_); } if (mysqli_connect_error()){ throw new ErrorException(mysqli_connect_error(),mysqli_connect_errno()); } # 문자셋 $chrset_is = parent::character_set_name(); if(strcmp($chrset_is,$chrset)) parent::set_charset($chrset); } #@ interface : ArrayAccess # 사용법 : $obj["two"] = "A value"; public function offsetSet($offset, $value) { $this->params[$offset] = parent::real_escape_string($value); } #@ interface : ArrayAccess # 사용법 : isset($obj["two"]); -> bool(true) public function offsetExists($offset) { return isset($this->params[$offset]); } #@ interface : ArrayAccess # 사용법 : unset($obj["two"]); -> bool(false) public function offsetUnset($offset) { unset($this->params[$offset]); } #@ interface : ArrayAccess # 사용법 : $obj["two"]; -> string(7) "A value" public function offsetGet($offset) { return isset($this->params[$offset]) ? $this->params[$offset] : null; } # @ interface : DBSwitch # :s1 -> :[문자타입]+[변수] # :s[문자], :d[정수], :f[소수], :b[바이너리] # 변수타입, :s1,:sa,:sA, :d1, :d2, :dA 어떻게든 상관없음 # 단 :s1, :s1 이렇게 중복 되어서는 안됨 # where 구문만 변경 // ("SELECT * FROM `TABLE` WHERE name=':s1' and age=':d2'",array('php',26,'나','ㅈㄷ',22)); public function bindParams($query,$args=array()){ if(strpos($query,':') !==false){ preg_match_all("/(\:[s|d|f|b])+[0-9]+/s",$query,$matches); if(is_array($matches)) { foreach($matches[0] as $n => $s) { # 문자타입과 값이 일치하는지 체크 $bindtype = substr($s,1,1); $bvmatched = false; switch($bindtype){ case 's': if(is_string($args[$n])) $bvmatched = true; break; case 'd': if(is_int($args[$n])) $bvmatched = true; break; case 'f': if(is_float($args[$n])) $bvmatched = true; break; case 'b': if(is_binary($args[$n])) $bvmatched = true; break; } if($bvmatched){ $query = str_replace($s,'%'.$bindtype,$query); $query = sprintf("{$query}",parent::real_escape_string($args[$n])); }else{ $query = false; break; } } } } return $query; } #@ return int # 총게시물 갯수 추출 public function get_total_record($table, $where="", $field='*'){ $wh = ($where) ? " WHERE ".$where : ''; if($result = parent::query('SELECT count('.$field.') FROM `'.$table.'`'.$wh)){ $row = $result->fetch_row(); return $row[0]; } return 0; } // 하나의 레코드 값을 가져오기 public function get_record($field, $table, $where){ $where = ($where) ? " WHERE ".$where : ''; $qry = "SELECT ".$field." FROM `".$table."` ".$where; if($result = $this->query($qry)){ $row = $result->fetch_assoc(); return $row; } return false; } # @ interface : DBSwitch public function query($query){ $result = parent::query($query); if( !$result ){ throw new ErrorException(mysqli_error(&$this).' '.$query,mysqli_errno(&$this)); } return $result; } # @ interface : DBSwitch # args = array(key => value) # args['name'] = 1, args['age'] = 2; public function insert($table){ $fieldk = ''; $datav = ''; if(count($this->params)<1) return false; foreach($this->params as $k => $v){ $fieldk .= sprintf("`%s`,",$k); $datav .= sprintf("'%s',", parent::real_escape_string($v)); } $fieldk = substr($fieldk,0,-1); $datav = substr($datav,0,-1); $this->params = array(); #변수값 초기화 $query = sprintf("INSERT INTO `%s` (%s) VALUES (%s)",$table,$fieldk,$datav); $this->query($query); } # @ interface : DBSwitch public function update($table,$where) { $fieldkv = ''; if(count($this->params)<1) return false; foreach($this->params as $k => $v){ $fieldkv .= sprintf("`%s`='%s',",$k,parent::real_escape_string($v)); } $fieldkv = substr($fieldkv,0,-1); $this->params = array(); #변수값 초기화 $query = sprintf("UPDATE `%s` SET %s WHERE %s",$table,$fieldkv,$where); $this->query($query); } # @ interface : DBSwitch public function delete($table,$where){ $query = sprintf("DELETE FROM `%s` WHERE %s",$table,$where); $this->query($query); } # 상속한 부모 프라퍼티 값 포함한 가져오기 public function __get($propertyName){ if(property_exists(__CLASS__,$propertyName)){ return $this->{$propertyName}; } } # db close public function __destruct(){ parent::close(); } } ? >
여기서 부터는
member 테이블이 있다고 가정하고
uid : 회원고유번호 userid : 아이디 name : 이름 passwd : 비밀번호 email : 이메일 정보 hp : 휴대폰
1. 데이타 입력
2. 데이타 쿼리
3. 데이타 수정
4. 데이타 삭제 예문을 보겠습니다.
1. insert 디비 저장 /-------------------
< ?php # 클래스 선언 $db = new DbMySqli(); # 디비 저장 $db['uid'] = 1; $db['userid'] = 'apmsoft'; $db['passwd'] = 'pwd1004'; $db['name'] = '멋쟁이'; $db['email'] = 'apmsoft@test.com'; $db['hp'] = '010-3456-9876'; $db->insert(); ? >
2. query 디비 쿼리 /---------------------------
/** 일반적인 복수의 데이타 쿼리문 */ < ?php # 디비 선언 $db = new DbMySqli(); # 쿼리 $result = $db->query("SELECT * FROM `member` WHERE uid='1'"); while( $row = $result->fetch_assoc() ) { echo $row['uid']; echo $row['userid']; echo $row['name']; } ? >
/** 단순 데이타 쿼리문 */ < ?php # 디비 선언 $db = new DbMySqli(); # 쿼리 $row = $db->get_record('*', 'member', "uid='1'"); echo $row['uid']; echo $row['userid']; echo $row['name']; ? >
3. update 디비 정보 수정 /----------------------------------
< ?php # 디비선언 $db = new DbMySqli(); # 디비정보 수정 $db['name'] = '홍길동'; $db['email'] = 'ddd@gmail.com'; $db->update('member', "uid='1'"); ? >
4. delete 디비 삭제 /----------------------------------------
< ?php # 디비선언 $db = new DbMySqli(); # 디비정보 삭제하기 $db->delete('member', "uid='1'"); ? >
'PHP > PHP5 클래스' 카테고리의 다른 글
php5 simple xml을 이용한 xml 파싱 클래스 (11) | 2012.05.10 |
---|---|
PHP5 Exception 예외처리 사용 방법과 그 종류 (0) | 2012.04.03 |