728x90

순수하게 PHP 코드만 들어간 경우에는 가독성이 좋은 편이지만,

HTML 코드와 같이 섞여 있는 경우에는 가독성이 떨어진다.

게다가 초보자는 에러를 만나면 해결하기가 참 난해하다.

 

이럴 경우에는 PHP 대체 문법을 사용하여 코딩하는 것이 좋다.


PHP는 제어 구조를 위해 대체 문법을 제공한다.

if, while, for, foreach, switch.

각 경우에 대체 문법의 기본형태는 괄호열기를 콜른 (:)으로 대체하고

괄호닫기는 각각 endif;, endwhile;, endfor;, endforeach;, endswitch; 로 대체한다.

 

 

<?php $i=0while($R = db_fetch_array($RCD)):?>
<tr>
    <td><input type="checkbox" name="post_members[]" value="<?php echo $R['uid']?>" /></td>
<td class="name"><?php echo $R['classname']?></td>
<td class="name">
        <a href="<?php echo $url?>/?mod=modify&amp;where=<?php echo $where?>&amp;keyword=<?php echo urlencode($keyword)?>
&amp;p=<?php echo $p?>&amp;uid=<?php echo $R['uid']?>"
 class="b" title="수정"><?php echo $R['name']?></a>  
</td>
<td class="name"><?php echo $R['classname']?></td>
<td class="name"><?php echo $R['classname']?></td>
<td class="name"><?php if($R['memo']) echo ($R['memo'])?></td>
<td class="name"><?php echo number_format($R['income'])?></td>
<td class="name"><?php echo number_format($R['outgoings'])?></td>
<td class="date"><?php echo $R['date']?></td>
</tr> 
<?php $i++; endwhile;?> 
 

if/elseif 조건을 콜론을 사용해서 정의할 때, else if 처럼 두 단어로 나눠서는 안된다.
PHP는 처리 오류로 실패한다.

 

<?php
/* 부적합한 방법: */
if($a > $b):
    echo $a." is greater than ".$b;
else if($a == $b): // 컴파일 되지 않는다.   

    echo $a." equals ".$b;

endif;

/* 적합한 방법: */
if($a > $b):
    echo $a." is greater than ".$b;
elseif($a == $b): // 단어가 붙어 있는 점에 주의.
    echo $a." equals ".$b;
else:
    echo $a." is neither greater than or equal to ".$b;
endif;

?>

 

HTML Entities(엔티티)는 HTML 태그와 혼용되는 것을 막기 위해 브라우저 상에 예약된 문자를 사용한다.

특수 문자(참조 문자)를 써야 하는 경우에는 이러한 엔티티 코드로 변환해서 입력해야 한다.

변환하지 않고 특수 문자를 그대로 입력해 버리면 컴퓨터가 문서를 읽을 때 실제 문서 내용(contents)과 코드를 구분하기 못하는 문제가 발생하기 때문이다.
가령, 어떤 문서 내용에 꺽쇠 괄호 ' < '가 포함돼 있다면, 컴퓨터는 이 문서를 읽어들일 때 꺽쇠 괄호를 HTML 태그의 시작 기호로 받아들여 버린다.
또 큰따옴표 ' " '는 HTML 속성 값으로 인식될 수 있고, ' & '은 엔티티 기호의 시작으로 인식될 수 있다.
때문에 이러한 혼동을 막으려면 특수 문자 대신 각 문자의 엔티티 코드를 써야 한다. 가장 흔한 실수는 URL 주소에 포함된 ' & ' 기호를 그대로 쓰는 경우이다.

&nbsp; ” ” : 공백(스페이스 한 칸)을 의미
& is HTML for "Start of a character reference".
 &lt;  부등호(<)
 &gt;  부등호(>)
 &amp;  앰퍼샌드(&) 기호
 &quot;  쌍따옴표(“)
 &#035;  sharp(#)
 &#039;  따옴표(‘)

 

좀 더 자세한 내용은 https://www.w3schools.com/html/html_entities.asp 를 참조하면 도움된다.

 

실제 사용하는 예제를 살펴보자.

테이블 안에 HTML 태그 사이에 실제 입력될 값을 PHP 대체문법으로 처리하여 깔끔하고 에러없이 원하는 결과를 얻을 수 있다는 걸 알 수 있다.

 

<?php
require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'dbDataClass.php';
require_once $g['path_class'].'bbsClass.php';
$b = new bbsClass();
$d = new DBDataClass();
 
$link_url = "contacts.php"// 현재 실행중인 파일명 가져오기
$page = isset($_GET['page'])? trim($_GET['page']):1;//페이지 변수 설정
$rowsPage = 10// 한 화면에 표시되는 게시글 수
$curPage = isset($_GET['p']) ? $_GET['p'] : 1;
$m = isset($_GET['m']) ? $_GET['m'] :'list';
 
$flddata ="uid,cat1,cat2,mobileNO,officeNO";// 화면에 출력할 칼럼 발췌
$where = isset($_GET['where']) ? $_GET['where']: '';
$keyword = isset($_GET['keyword']) ? $_GET['keyword']: '';
$xorderbyisset($xorderby) ? $xorderby : 'cat1 ASC, cat2 ASC'// 없는 칼럼인지 꼭 체크하라.
 
$sqlque = 'display=1';
if ($cat1$sqlque .= ' and cat1='.$cat1;
if ($cat2$sqlque .= ' and cat2='.$cat2;
 
if($where && $keyword) {
    if($where == 'telNO') {
        $sqlque .= " and (mobileNO LIKE '%".$keyword."%' OR officeNO LIKE '%".$keyword."%') ";
    }
}
//echo $sqlque.'<br/>';
 
$g['url_link']=($m?'m='.$m.'&amp;':'').($where?'where='.$where.'&amp;':'').($keyword?'keyword='.urlencode(stripslashes($keyword)).'&amp;':'');
$g['bbs_reset'= $link_url.'?'.($m?'m='.$m.'&amp;':'');
 
$table ='members'// 테이블
$rows$d->getDbArray($table,$sqlque,$flddata,$xorderby,$rowsPage,$curPage);
$NUM = $d->getDbRows($table,$sqlque); // 전체 게시글수
$TPG = $b->getTotalPage($NUM,$rowsPage);
$i = 0;
?>
<div class="table-responsive text-nowrap">
<div class="float-left info">
    <?php if$keyword ):?><strong>"<?php echo $keyword?>"</strong> 검색결과 : <?php endif?>
    <?php echo number_format($NUM)?>개 (<?php echo $curPage;?>/<?php echo $TPG;?>페이지)
</div>
 
<table id="ListTable" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
    <thead align='center'>
        <tr>
            <th scope="col">No</th>
            <th scope="col">구분1</th>
            <th scope="col">구분2</th>
            <th scope="col">휴대폰번호</th>
            <th scope="col">사무실번호</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($rows as $R):?>
        <?php
            $CA1$d->getDbData('cate','id="'.$R['cat1'].'" and parent_id=0','name');
            $CA2$d->getDbData('cate','id="'.$R['cat2'].'" and parent_id="'.$R['cat1'].'"','name');
            $no = $NUM - (($curPage - 1* $rowsPage- $i;
            $i++;
        ?>
        <tr id="<?php echo $R['uid']; ?>">
            <td><?php echo $no;?></td>
            <td><?php echo $CA1['name'];?></td>
            <td><?php echo $CA2['name'];?></td>
            <td><a href="tel:<?php echo $R['mobileNO'];?>"><i class="fas fa-phone"></i></a></td>
            <td><a href="tel:<?php echo $R['officeNO'];?>"><i class="fas fa-phone"></i></a></td>
        </tr>
        <?php endforeach;?>
    </tbody>
</table>
 
<div class='form-group'>
    <form name="Form" class="form-inline" action="<?php echo $link_url;?>">
        <input type="hidden" name="m" value="<?php echo $m;?>" />
        <input type="hidden" name="cat1" value="<?php echo $cat1;?>" />
        <input type="hidden" name="cat2" value="<?php echo $cat2;?>" />
        <input type="hidden" name="orderby" value="<?php echo $xorderby;?>" />
 
        <div class="input-group mb-3">
            <select name="where" class="browser-default custom-select">
                <option value="telNO">전화번호</option>
            </select>
        </div>
        <div class="input-group mb-3">
          <input type="text" name="keyword" class="form-control" id="SearchKeyword">
          <div class="input-group-append">
            <button class="btn btn-md" type="button" id="Search">검색</button>
            <button class="btn btn-md" type="button" id="Home">Home</button>
          </div>
        </div>
    </form>
</div>
 
<?php $b->PageLinkView($link_url,$NUM,$rowsPage,$curPage,$g['url_link']);?>
</div>

 

 

 

<table id="AccessLogListTable" class="table table-striped table-bordered table-hover table-sm" cellspacing="0" width="100%">
    <thead align='center'>
        <tr>
            <th scope="col">No</th>
            <th scope="col">IP주소</th>
            <th scope="col">날짜</th>
            <th scope="col">시간</th>
            <th scope="col">OS</th>
            <th scope="col">Browser</th>
            <th scope="col">userID</th>
            <th scope="col">userNM</th>
            <th scope="col">성공/실패</th>
            <th scope="col">접속루트</th>
            <th scope="col">에러코드</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($rows as $R):?>
        <?php
            $no = $NUM - (($curPage - 1) * $rowsPage) - $i;
            $i++;
        ?>
        <tr id="<?php echo $R['uid']; ?>">
            <td><?php echo $no;?></td>
            <td><?php echo $a->IPaddressMasking($R['ipaddr']);?></td>
            <td><?php echo $a->displayDate($R['date']);?></td>
            <td><?php echo $R['time'];?></td>
            <td><?php echo $R['OS'];?></td>
            <td><?php echo $R['browser'];?></td>
            <td><?php echo $a->IDMasking($R['userID']);?></td>
            <td><?php echo strlen($R['userNM'])>0 ? $a->letterMasking($R['userNM']):'';?></td>
            <td><?php echo $R['success'];?></td>
            <td><?php echo $R['route'];?></td>
            <td><?php echo $errorArr[$R['errCode']];?></td>
        </tr>
        <?php endforeach;?>
    </tbody>
</table>

 

'Web 프로그램 > PHP 문법' 카테고리의 다른 글

PHP Class 개념 이해 ★★  (0) 2017.01.10
PHP isset 과 empty 설명  (1) 2016.04.27
[PHP] switch 문  (0) 2015.06.01
[PHP] 문자열 자르기 substr  (0) 2015.05.16
음악 재생 1  (0) 2015.03.28
블로그 이미지

Link2Me

,