검색결과 리스트
PHP5에 해당되는 글 4건
- 2012.05.10 php5 simple xml을 이용한 xml 파싱 클래스 11
- 2012.04.03 PHP5 Exception 예외처리 사용 방법과 그 종류
- 2012.04.03 php5 autoload 활용하기
- 2012.03.20 php5 mysqli 디비 접속 클래스 프로그램 및 사용법
글
php5 simple xml을 이용한 xml 파싱 클래스
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 예외처리 사용 방법과 그 종류
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 autoload 활용하기
PHP5 autoload 함수 활용하기
PHP5 부터는 __autoload 라는 특별한 함수를 지원한다.
기존의 클래스 파일을 사용하기 위해서는
include '/classes/db/DbMysqli.class.php';
$db = new DbMysqli();
이와 같이 include 먼저 하고나서
클래스를 선언하여 사용해야 했다.
엄청 불편하다
자바처럼 그냥 new 로 생성해서 사용하면 편한데 말이다. ^^
그래서 나온것이 바로 요놈 __autoload 이다
이놈을 사용하게 되면
그냥 include 를 수동으로 코딩하지 않아도
__autoload 이놈이 알아서 include 해준다.
그러므로 이제부터는 그냥
$db = new DbMysqli();
이렇게만 선언해서 사용하면 된다.
아래 소스는 __autoload 를 정의 해 놓은 것이다
소스는 이렇다
@ __autoload Source
# 절대 경로 define('_ROOT_PATH_', '/www/설치경로'); # 클래스 자동 인클루드 function __autoload($class_name) { # 클래스명중 경로 추출 $tmp_args = explode(' ', preg_replace( '/([a-z0-9])([A-Z])/', "$1 $2",$class_name)); $class_path_name = sprintf("%s/{$class_name}",strtolower($tmp_args[0])); # 체크 if(!class_exists($class_path_name,false)) { # classes 폴더 if(file_exists(_ROOT_PATH_.'/classes/'.$class_path_name.'.class.php') !==false){ include_once _ROOT_PATH_.'/classes/'.$class_path_name.'.class.php'; } # modules 폴더 else if(file_exists(_ROOT_PATH_.'/modules/'.$class_path_name.'.class.php') !==false){ include_once _ROOT_PATH_.'/modules/'.$class_path_name.'.class.php'; } # 기타 만든 클래스 폴더 [첫대문자만 폴더로 지원] # ( /my/MyTest.class.php -> MyTest.class.php) else if(file_exists(_ROOT_PATH_.'/'.$class_path_name.'.class.php') !==false){ include_once _ROOT_PATH_.'/'.$class_path_name.'.class.php'; } } }
자 이젠 __autoload 함수 정의 해 놓은 것을 설명할 차례군요
먼저, 아래와 같은 폴더 구조에 클래스 파일들이 있다고 가정을 합니다.
|----------------------------------------------------------------
| 파일경로 및 클래스 파일명 | 클래스명
|-----------------------------------+----------------------------
/classes/db/DbMysqli.class.php // class DbMysqli{ }
/classes/req/ReqForms.class.php // class
ReqForms { }
/classes/tpl/TplFusion.class.php // class
TplFusion {}
/modules/bbs/BbsModel.class.php // class BbsModel{ }
/modules/mem/MemModel.class.php // class MemModel{ }
/my/MyTest.class.php // class MyTest{ }
1. __autoload($class_name) 는 new 라는 명령만 떨어지면 자동으로 호출이 됩니다.
$db = new DbMysqli();
new -> __autoload 를 호출하고
$class_name -> DbMysqli 클래스 명이 되는거죠
2. 클래스명에서 클래스가 위치 하고 있는 경로를 추출합니다. 기준은 첫번째 대문자로 시작하고
다음 대문자가 나오기 전까지의 클래스명의 문자는 폴더를 가리킵니다.
DbMysqli 이건 폴더 db 를 가리키고
ReqForms 이건 폴더 req 를 가리키고
BbsModel 이건 폴더 bbs 를 가리키고
MemModel 이건 폴더 Mem 를 가리키고
MyTest 이건 폴더 my 를 가리킵니다.
위와 같은 기준으로 위치 (폴더) 를 알아냅니다.
# 클래스명중 경로 추출 $tmp_args = explode(' ', preg_replace( '/([a-z0-9])([A-Z])/', "$1 $2",$class_name)); $class_path_name = sprintf("%s/{$class_name}",strtolower($tmp_args[0]));
2. 이미지 인클루드된 클래스 파일이 있는지 확인 한 후 있으면 include 안하고
없으면 하게 될겁니다.
제가 코딩 해 놓은건
일단 무조건
1. classes 폴더 밑에 클래스 이름 폴더를 찾고 없으면
2. modules 폴더 밑에 클래스 이름 폴더를 찾고 그리고 나서
3. 선언된 클래스의 이름 폴더를 찾도록 하였습니다.
전 이유가 있어서 그랬지만 1,2번을 삭제하고 바로 3번만 선언해서 사용하셔도 됩니다.
그 역할을 하는 소스 부분이 바로 이 부분
# 체크 if(!class_exists($class_path_name,false)) { # 1. classes 폴더 if(file_exists(_ROOT_PATH_.'/classes/'.$class_path_name.'.class.php') !==false){ include_once _ROOT_PATH_.'/classes/'.$class_path_name.'.class.php'; } # 2. modules 폴더 else if(file_exists(_ROOT_PATH_.'/modules/'.$class_path_name.'.class.php') !==false){ include_once _ROOT_PATH_.'/modules/'.$class_path_name.'.class.php'; } # 3. 기타 만든 클래스 폴더 [첫대문자만 폴더로 지원] # ( /my/MyTest.class.php -> MyTest.class.php) else if(file_exists(_ROOT_PATH_.'/'.$class_path_name.'.class.php') !==false){ include_once _ROOT_PATH_.'/'.$class_path_name.'.class.php'; } }
끝까지 읽어 주셔서 감사합니다.
이 방법 말고도 php.net 에 보시면 클래스도 지원합니다.
마음에 드는 방법으로 사용하세요
'PHP > 팁앱테크' 카테고리의 다른 글
php 문서 안에 HTML 문서 쉽게 넣기 (0) | 2012.06.08 |
---|---|
PHP 제어 구문과 문법 (0) | 2012.04.03 |
php array 값중 가장 큰 값을 추출(max)하고 그 값이 가리키고 있는 키값(array_search)을 추출한다 (0) | 2012.03.29 |
php array 함수의 마력 array_splice, array_values 활용 (0) | 2012.03.29 |
abcd1004 중 뒤의 숫자만 추출하기 (0) | 2012.03.21 |
설정
트랙백
댓글
글
php5 mysqli 디비 접속 클래스 프로그램 및 사용법
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 |