728x90

https://mdbootstrap.com/docs/b4/jquery/javascript/charts/

 

Bootstrap Charts Guideline - examples & tutorial

Bootstrap charts are graphical representations of data. Charts come in different sizes and shapes: bar, line, pie, radar, polar and more.

mdbootstrap.com

기본적인 예제가 나와 있다.

이 예제를 가지고 DB와 연동하여 처리하는 방법이다.

 

 

<?php
error_reporting(0);
//*
ini_set("display_startup_errors"1);
ini_set("display_errors"1);
error_reporting(E_ALL);
// */
 
require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php'// 세션 체크
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'statsClass.php';
$b = new statsClass();
 
$link_url = "Stats.php"// 현재 실행중인 파일명 가져오기
 
$ageData = $b->ageCnt_array();
 
?>
<p class="h4 mb-4">통계</p>
<div class="row">
    <div class="col-md-8 col-xl-8 col-lg-7">
        <div class="col-md-11">
            <canvas id="Trend1Chart"></canvas>
        </div>
        <div class="col-md-11  mb-4">
            
        </div>
        <div class="col-md-11">
            <canvas id="Trend3Chart"></canvas>
        </div>
    </div>
 
    <div class="col-md-4 col-xl-4 col-lg-5">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">연령대</h6>
            </div>
            <div class="card-body">
                <div class="chart-pie pt-4">
                    <canvas id="ageChart"></canvas>
                </div>
            </div>
        </div>
 
    </div>
</div>
 
<script>
  var ctxD = document.getElementById("ageChart").getContext('2d');
  var ageKey = <?php echo json_encode(array_keys($ageData));?>;
  var ageData = <?php echo json_encode(array_values($ageData));?>;
  var myLineChart = new Chart(ctxD, {
    type: 'doughnut',
    data: {
      labels: ageKey,
      datasets: [{
        data: ageData,
        backgroundColor: ["#F7464A""#46BFBD""#FDB45C""#949FB1""#4D5360"],
        hoverBackgroundColor: ["#FF5A5E""#5AD3D1""#FFC870""#A8B3C5""#616774"]
      }]
    },
    options: {
      responsive: true
    }
  });
</script>

 

PHP 배열을 Javascript 변수로 사용하는 방법이 핵심이다.

 

PHP에서 생성된 배열을 자바스크립트에서 사용하는 방법

<?php
$arr_php = array("a","b","c","d");
?>

위 값처럼 선언된 배열을 javascript에서 받아서 사용하려면?

var arr_js = <?php echo json_encode($arr_php)?>;

json_encode 해서 받으면 된다.

json_encode 함수를 사용하면 1차원 배열이든 2차원 배열이든 간단하게 자바스크립트 배열로 만들어 준다.

array_keys($array)  : 배열의 키값을 배열로 반환해주는 함수

array_values($array)  : 배열의 값을 배열로 반환해주는 함수
 
아래 statsClass 의 함수 구현한 것을 살펴보면 PHP 배열을 key, value 로 된 형태로 반환하는 것을 알 수 있다.
<?php
class statsClass {
    function ageCnt_array(){
        global $db;
        $sql = "select age, sum(Cnt) from stats group by age";
        $result = mysqli_query($db,$sql);
        $R=array();
        $TCNT = $this->ageTotalCnt();
        while($row = mysqli_fetch_row($result)){
            $row[0= $row[0].'('.$this->Percentage($row[1],$TCNT).'%)';
            $R[$row[0]] = $row[1];
        }
        return $R// 배열로 반환
    }
 
    function ageTotalCnt(){
        global $db;
        $sql = "select sum(Cnt) from stats";
        $result = mysqli_query($db,$sql);
        if($row = mysqli_fetch_row($result)){
            return $row[0];
        }
    }
 
    function Percentage($val,$TCNT){
        $percent = $val / $TCNT * 100;
        return round($percent,1);
    }
 
}
?>

 

 

블로그 이미지

Link2Me

,

MDB4 select

Web 프로그램/MDB 2022. 2. 12. 21:34
728x90

mdbootstrap4 기반 select

https://mdbootstrap.com/docs/b4/jquery/forms/select/

 

Bootstrap Select - examples & tutorial. Basic & advanced usage

Bootstrap select is a form control which after a click displays a collapsable list of multiple values which can be used in forms, menus or surveys.

mdbootstrap.com

<select class="browser-default custom-select">
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

 

 

MySQL DB 기반 select

 

<?php
require_once 'config.php';
require_once 'dbconnect.php';
 
$sql = "SELECT DISTINCT YM FROM customer ORDER BY YM DESC LIMIT 3";
$result = mysqli_query($db$sql);
?>
 
<form id="form" class="text-center border border-light p-5">
 
    <p class="h4 mb-4">Data 업데이트</p>
 
    <select class="browser-default custom-select" name="ym">
      <option value="" selected>-년월-</option>
    <?php
    while($R = mysqli_fetch_row($result)):
        echo '<option value="'.$R[0].'">'.$R[0].'</option>';
    endwhile;
    ?>
    </select>
 
    <div>
        <button type="submit" id="btnSubmit" class="btn btn-outline-default">전송</button>
        <button type="reset" id="btnReset" class="btn btn-outline-default">취소</button>
    </div>
    <br/>
</form>
 
<script>
$('#form').submit(function(e) {
    e.preventDefault();
    var yearmonth = $("select[name=ym]").val();
    if(yearmonth == '') {
        alert('연월을 선택하세요');
        $("select[name=ym]").focus();
        return false;
    }
 
    $.ajax({
        url: phpUpfilename,
        type: 'POST',
        data: { YM : yearmonth },
        dataType: 'text',
        success: function (data) {
            console.log(data);
            alert(data);
        },
        error: function(data) {
            alert("error in ajax form submission");
        }
    });
});
</script>
 

 

 

 

 

블로그 이미지

Link2Me

,
728x90

MDB 템플릿을 사용하다가 정보 찾는데 걸리는 시간을 절약하기 위해 적어둔다.

bootstrap4 기반으로 만들어진 템플릿이라 bootstrap4 용일 수도 있다.

 

글자 굵은 글씨

<b class="font-weight-bold">'.$R['jiAddress'].' '.$R['aDong'].$bldNM).'</b>

 

글자 왼쪽 정렬

<td class="text-left"><?php echo $R['content'];?></td>

 

빨간 글씨

<td class="text-danger"><?php echo $R['content'];?></td>

 

<?php if($mtype==3):?><td><?php echo $R['d_regis'];?></td><?php endif;?>

 

<tr>
    <th class="text-left" style='width:80pt'>인입구배선</th>
    <td class="text-left" style='width:85%'>
        <div class="form-check form-check-inline">
          <input type="radio" class="form-check-input" name="wireEnt" id="wireEnt1" value="1" <?php if(!isset($C['wireEnt'])):?>checked<?php elseif($C['wireEnt'] == "1"):?>checked<?php else:?><?php endif?>>
          <label class="form-check-label" for="wireEnt1">O</label>
        </div>
        <div class="form-check form-check-inline">
          <input type="radio" class="form-check-input" name="wireEnt" id="wireEnt2" value="2" <?php if(!isset($C['wireEnt'])):?><?php elseif($C['wireEnt'] == "2"):?>checked<?php else:?><?php endif?>>
          <label class="form-check-label" for="wireEnt2">X</label>
        </div>
        <div class="form-check form-check-inline">
          <input type="radio" class="form-check-input" name="wireEnt" id="wireEnt3" value="3" <?php if(!isset($C['wireEnt'])):?><?php elseif($C['wireEnt'] == "3"):?>checked<?php else:?><?php endif?>>
          <label class="form-check-label" for="wireEnt3">△</label>
        </div>
        <div class="form-check form-check-inline">
          <input type="radio" class="form-check-input" name="wireEnt" id="wireEnt4" value="4" <?php if(!isset($C['wireEnt'])):?><?php elseif($C['wireEnt'] == "4"):?>checked<?php else:?><?php endif?>>
          <label class="form-check-label" for="wireEnt4">해당없음</label>
        </div>
    </td>
</tr>

 

 

 

 

 

 

블로그 이미지

Link2Me

,
728x90

Class 를 만들어서 사용하면 여러모로 편하고 좋다.

본 Class 함수는 KIMSQ RB에서 사용하는 함수를 Class화해서 사용하고 있다.

그만큼 코딩을 편하면서도 깔끔하게 이해하게 해준다.

MDB(Meterial Design for Bootstrap) 든 일반 게시판이든 사용하는데는 다 사용 가능하다. MDB는 템플릿으로 깔끔하게 보여주기 때문에 디자인에 대한 고민을 덜어준다.


<?php

// 파일명 : dbDataClass.php

class DBDataClass {
    //DB-UID데이터
    function getUidData($table,$uid)
    {
        return $this->getDbData($table,'uid='.(int)$uid,'*'); // 'uid='.(int)$uid
    }

    // DB Query Cutom 함수
    function getDbData($table,$where,$column) {
        global $db;
        $sql ='select '.$column.' from '.$table.($where?' where '.$this->getSqlFilter($where):'');
        //echo $sql; // 디버깅 목적으로 필요할 때가 있다.
        $result = mysqli_query($db,$sql);
        $row = mysqli_fetch_array($result);
        return $row;
    }

    // DB Query result 함수
    function getDbresult($table,$where,$column) {
        global $db;
        $sql = 'select '.$column.' from '.$table.($where?' where '.$this->getSqlFilter($where):'');
        $result = mysqli_query($db,$sql);
        return $result;
    }

    //DB데이터 ARRAY -> 테이블에 출력할 데이터 배열
    function getDbArray($table,$where,$flddata,$orderby,$rowsPage,$curPage){
        global $db;
        $sql ='select '.$flddata.' from '.$table.($where?' where '.$this->getSqlFilter($where):'').($orderby?' order by '.$orderby:'').($rowsPage?' limit '.(($curPage-1)*$rowsPage).', '.$rowsPage:'');
        //echo $sql;
        $result = mysqli_query($db,$sql);
        return $result;

    }

    //DB데이터 레코드 총 개수
    function getDbRows($table,$where){
        global $db;
        $sql = 'select count(*) from '.$table.($where?' where '.$this->getSqlFilter($where):'');
        $result = mysqli_query($db,$sql);
        if($result){
            $rows = mysqli_fetch_row($result);
            return $rows[0] ? $rows[0] : 0;
        } else {
            echo "Failed to connect to MySQL: " . mysqli_connect_error($db);
            exit(); // **this is missing**
        }
    }

    //DB삽입
    function getDbInsert($table,$key,$val){
        global $db;
        $sql ="insert into ".$table." (".$key.")values(".$val.")";
        //echo $sql;
        if(mysqli_query($db,$sql)){
            return 1;
        } else {
            return 0;
        }
    }

    //DB업데이트
    function getDbUpdate($table,$set,$where){
        global $db;
        mysqli_query($db,'set names utf8');
        mysqli_query($db,'set sql_mode=\'\'');
        $sql ="update ".$table." set ".$set.($where?' where '.$this->getSqlFilter($where):'');
        if(mysqli_query($db,$sql)){
            return 1;
        } else {
            return 0;
        }
    }

    //DB삭제
    function getDbDelete($table,$where)    {
        global $db;
        $sql ="delete from ".$table.($where?' where '.$this->getSqlFilter($where):'');
        if(mysqli_query($db,$sql)){
            return 1;
        } else {
            return 0;
        }
    }

    //SQL필터링
    function getSqlFilter($sql)    {
        return $sql;
    }

    // 암호화
    function AES_Encode($plain_text){
        global $key;
        return base64_encode(openssl_encrypt($plain_text, "aes-256-cbc", $key, true, str_repeat(chr(0), 16)));
    }

    // 복호화
    function AES_Decode($base64_text){
        global $key;
        return openssl_decrypt(base64_decode($base64_text), "aes-256-cbc", $key, true, str_repeat(chr(0), 16));
    }

}//end dbClass

?>


블로그 이미지

Link2Me

,
728x90

파일 삭제 처리하는 로직 구현이다.

<?php
require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php';
require_once $g['path_root'].'deviceChk.php';
if($mtype == 3){
    require_once $g['path_root'].'ipFiltering.php';
}
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'dbDataClass.php';
$d = new DBDataClass;

if(!isset($_GET['idx']) || empty($_GET['idx'])){
    $rs=0;
} else {
    // 등록자 여부 체크
    $R = $d->getUidData('bbs_data',$_GET['idx']);
    if($R['userID'] == $_SESSION['userID'] || (isset($_SESSION['authID']) && ($_SESSION['authID']==1 || $_SESSION['authID']==2))){
        // 등록자 또는 관리자(관리자, 최고관리자) 인 경우에는 삭제 가능
        $rs=$d->getDbDelete('bbs_data', 'uid='.$_GET['idx'].'');
        $d->getDbDelete('bbs_comment', 'parentid='.$_GET['idx'].''); //댓글 같이 삭제됨
    } else {
        $rs = -2;
    }
}
echo $rs;
?>


블로그 이미지

Link2Me

,
728x90

게시판 기능을 구현하고 있는데, 코딩 구현보다 Layout 기능 익히는 게 더 힘들어서 적어둔다.

기능 구현이 끝나면 수정해야 할 부분(보안 문제 고려사항)

error_reporting(E_ALL);
ini_set("display_errors", 1);


error_reporting(0); 로 변경해야 한다.

 

<?php

// 파일명 : bbsView.php
error_reporting(E_ALL);
ini_set("display_errors", 1);

require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php';
require_once $g['path_root'].'deviceChk.php';
if($mtype == 3){
    require_once $g['path_root'].'ipFiltering.php'; // PC접속은 IP 접속 허용이 된 경우에만 접속 가능
}
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'dbDataClass.php';
require_once $g['path_class'].'bbsClass.php';
$c = new bbsClass();
$d = new DBDataClass();

$bid = isset($_GET['bid']) ? $_GET['bid']: '';
$curPage = isset($_GET['p']) ? $_GET['p'] : 1;

$R = $d->getDbData('bbs_data', 'uid="'.$_GET['uid'].'"', '*');
$html = ($R['html'] == 1) ? 'HTML' : 'TEXT';

 

// 쿠키를 이용한 조회수 중복 방지
if(!empty($R['uid']) && empty($_COOKIE['bbs_data_'.$R['uid']])) {
    if(strcmp($_SESSION['userID'],$R['userID']) !== 0){ // 등록자 본인이 아니면
        $d->getDbUpdate('bbs_data','hit=hit+1','uid='.$R['uid']);
        setcookie('bbs_data_'.$R['uid'], TRUE, time() + (60 * 60 * 24), '/');
    }
}

?>
<table class="table table-bordered table-hover table-sm" cellspacing="0" width="100%">
    <tr>
        <td style="width:70px;">제목</td>
        <td class="text-left"><?php echo $R['subject']?></td>
    </tr>
    <tr>
        <td>내용</td>
        <td class="text-left"><?php echo $c->getContents($R['content'],$html);?></td>
    </tr>
</table>

<?php include_once $g['path_bbs'].'bbsComment.php';?>

 

<div class="table-responsive text-nowrap">
    <div class="float-left info">
        <button class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" type="button" id="BBSHome">목록</button>
    </div>
    <div class="float-right info">
        <?php if($R['userID'] == $_SESSION['userID'] || (isset($_SESSION['authID']) && $_SESSION['authID']==1 )):?>
        <a href="bbsWrite.php" class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" id="bbsModify" data-id="<?=$R['uid'];?>" curPage="<?=$curPage;?>">수정</a>
        <button class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" type="button" id="bbsDelete" data-id="<?=$R['uid'];?>" curPage="<?=$curPage;?>">삭제</button>
        <?php endif;?>
    </div>
</div> 

 

bbsComment.php ==> 댓글 달기 및 댓글 보기

<?php

// 파일명 : bbsComment.php

error_reporting(E_ALL);
ini_set("display_errors", 1);

require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php';
require_once $g['path_root'].'deviceChk.php';
if($mtype == 3){
    require_once $g['path_root'].'ipFiltering.php';
}
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'dbDataClass.php';
$d = new DBDataClass();

?>

<div class="form-group">
    <form name="commentForm" class="form-inline">
        <input type="hidden" name="mode" value="new" />
        <input type="hidden" name="parentid" value="<?php echo $_GET['uid'];?>" />
        <input type="hidden" name="userID" value="<?php echo $_SESSION['userID'];?>" />
        <input type="hidden" name="userNM" value="<?php echo $_SESSION['userNM'];?>" />
        <input type="hidden" name="p" value="<?=$curPage;?>" />

        <div class="input-group mb-3" style="width:100%;">
          <input type="text" name="comment" class="form-control" placeholder="댓글을 입력하세요" aria-label="comment"
            aria-describedby="comment_form">
          <div class="input-group-append">
            <button type="button" class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" id="comment_form">댓글</button>
          </div>
        </div>

    </form>
</div>

<div class="table-responsive text-nowrap">
<table class="table table-hover table-sm" cellspacing="0" width="100%">
    <tbody>
    <?php $COMM = $d->getDbArray('bbs_comment','parentid="'.$_GET['uid'].'"','*','uid DESC',0,1);?>
    <?php while($C = mysqli_fetch_array($COMM)):?>
        <tr id="<?php echo $C['uid'];?>">
            <td class="text-left"><?php echo $C['userID'];?></td>
            <td class="text-left"><?php echo $C['comment'];?></td>
            <td><?php echo substr($C['d_regis'],0,8);?></td>
            <td>
            <button class="btn btn-md m-0 z-depth-0 comment_del" type="button" title='삭제'>&times;</button>
            </td>
        </tr>
    <?php endwhile;?>
    </tbody>
</table>
</div>

<?php
// 파일명 : bbsCommentChk.php
if(!isset($_SESSION)){
    session_start();
}
//echo '<pre>';print_r($_POST);echo '</pre>';
//exit;
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST"){
    @extract($_POST);
    require_once 'path.php';// root 폴더를 기준으로 상대경로 자동 구하기
    require_once $g['path_config'].'dbconnect.php';
    require_once $g['path_class'].'dbDataClass.php';
    $d = new DBDataClass(); // AES_Decode()

    $comment = trim($comment);
    date_default_timezone_set('Asia/Seoul');

    if($mode == 'new'){
        $d_regis = date('YmdHis');
        $access_ip=$_SERVER['REMOTE_ADDR'];
        $QKEY = "parentid,comment,d_regis,userID,userNM,ip";
        $QVAL = "'$parentid','$comment','$d_regis','$userID','$userNM','$access_ip'";
        $d->getDbInsert('bbs_comment',$QKEY,$QVAL);
        echo 1;
    } else {
        // 등록자 여부 체크
        $R = $d->getUidData('bbs_comment',$uid);
        if($R['userID'] == $_SESSION['userID']){
            $QSET="comment='".$comment."'";
            $QVAL="uid='".$uid."'";

            $d->getDbUpdate('bbs_data',$QSET,$QVAL);
            echo 2;
        } else {
            echo -2;
        }
    }
} else {
    echo -1;
}
?>

<?php
// 파일명 : bbsCommentDelete.php
require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php';
require_once $g['path_root'].'deviceChk.php';
if($mtype == 3){
    require_once $g['path_root'].'ipFiltering.php';
}
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'dbDataClass.php';
$d = new DBDataClass;

if(!isset($_GET['idx']) || empty($_GET['idx'])){
    $rs=0;
} else {
    // 등록자 여부 체크
    $R = $d->getUidData('bbs_comment',$_GET['idx']);
    if($R['userID'] == $_SESSION['userID'] || (isset($_SESSION['authID']) && ($_SESSION['authID']==1 || $_SESSION['authID']==2))){
        // 등록자 또는 관리자(관리자, 최고관리자) 인 경우에는 삭제 가능
        $rs=$d->getDbDelete('bbs_comment', 'uid='.$_GET['idx'].'');
    } else {
        $rs = -2;
    }
}
echo $rs;
?>

 

jQuery 처리 부분은 https://link2me.tistory.com/1665 를 참조하면 된다.

 

블로그 이미지

Link2Me

,
728x90

게시판에서 등록한 글을 MySQL DB에 저장하는 로직 구현이다.

jQuery 와 연동하여 처리하므로 MySQL DB에 등록되지 전에 값이 제대로 잘 전달되는지 체크하는 걸 시도한다.

echo '<pre>';print_r($_POST);echo '</pre>';
exit;


POST 변수가 문제없이 잘 전달되었으면 이제 관련 코드를 아래와 같이 구현했다.

게시판을 완벽하게 처리하는 것은 아니고 1단에 대한 값만 등록하고, 게시글이 등록되었을 때 관리자에게 메일이 전달되도록 하는 걸 추가했다.


<?php
if(!isset($_SESSION)){
    session_start();
}
//echo '<pre>';print_r($_POST);echo '</pre>';
//exit;
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST"){
    @extract($_POST);
    require_once 'path.php';// root 폴더를 기준으로 상대경로 자동 구하기
    require_once $g['path_config'].'dbconnect.php';
    require_once $g['path_class'].'dbDataClass.php';
    require_once $g['path_class'].'bbsClass.php';
    $d = new DBDataClass();
    $c = new bbsClass();

    if($mode == 'write'){
        $subject = trim($subject);
        $content = trim($content);
        $html = 0;
        $depth = 1;
        $notice = 0;
        date_default_timezone_set('Asia/Seoul');

        if($uid == 0){
            $d_regis = date('YmdHis');
            $access_ip=$_SERVER['REMOTE_ADDR'];
            $QKEY = "bbsid,subject,content,html,depth,notice,d_regis,userID,userNM,ip";
            $QVAL = "'$bid','$subject','$content',$html,$depth,$notice,'$d_regis','$userID','$userNM','$access_ip'";
            $d->getDbInsert('bbs_data',$QKEY,$QVAL);
            Mail2Admin($subject,$content);
            echo 1;
        } else {
            // 등록자 여부 체크
            $R = $d->getDbData('bbs_data','uid='.$uid,'*');
            if($R['userID'] === $_SESSION['userID']){ // 관리자도 수정은 불가
                $QSET="subject='".$subject."',";
                $QSET.="content='".$content."',";
                $QSET.="html='".$html."'";
                $QVAL="uid='".$uid."'";

                $d->getDbUpdate('bbs_data',$QSET,$QVAL);
                echo 2;
            } else {
                echo -2;
            }
        }
    } else if($mode == 'delete'){
        $d->getDbDelete('bbs_data',"uid='".$uid."'");
        echo 3; // 삭제
    }
} else {
    echo -1;
}

function Mail2Admin($subject,$message){
    global $c;
    $to = "jsk005@naver.com";
    $from = "webmaster@abc.com";
    $nameFrom = "AppMaster";
    $message = $c->getContents($message,'TEXT');

    $mailheaders = "Return-Path: $from\r\n";
    $mailheaders.= "From: $nameFrom <$from>\r\n";
    $mailheaders.= "Content-Type: text/html;charset=utf-8\r\n";
    $mailheaders.= "MIME-Version: 1.0\r\n";

    mail($to, $subject, $message, $mailheaders, $from);
}
?>

function getContents($str,$html){
    if ($html == 'HTML'){
        $str = htmlspecialchars_decode(stripslashes($str));
        $str = str_replace('<A href=','<a target="_blank" href=',$str);
        $str = str_replace('<a href=','<a target="_blank" href=',$str);
        $str = str_replace('<a target="_blank" href="#','<a href="#',$str);
        $str = str_replace(' target="_blank">','>',$str);
        $str = str_replace('< param','<param',$str);
        $str = str_replace("\t",'&nbsp;&nbsp;&nbsp;&nbsp;',$str);
        $str = str_replace('@IFRAME@','iframe',$str);

        $str = str_replace('imgOrignWin(this.src)=""','onclick="imgOrignWin(this.src);"',$str);
        $str = str_replace('imgorignwin(this.src)=""','onclick="imgOrignWin(this.src);"',$str);
        $_atkParam = array(';a=','&a=','?a=','m=admin','system=');
        foreach($_atkParam as $_prm){
            $str = str_replace($_prm,'',$str);
        }
    }
    else {
        $str = str_replace('<','&lt;',$str);
        $str = str_replace('>','&gt;',$str);
        $str = str_replace('&nbsp;','&amp;nbsp;',$str);
        $str = str_replace("\t",'&nbsp;&nbsp;&nbsp;&nbsp;',$str);
        $str = nl2br($str);
    }
    return $str;
}



블로그 이미지

Link2Me

,
728x90

MDB(Meterial Design for Bootstrap4) 게시판을 만드는 골격과 jQuery 내용이다.

Bootstrap4 기본 문법 사항은 https://www.w3schools.com/bootstrap4/default.asp 에 잘 나와 있다.

그리고 MDB 는 https://mdbootstrap.com/ 를 수시로 참조하면 템플릿 구성을 깔끔하게 만들 수 있다.

유료 템플릿을 구입하여 사용하고 있기 때문에 무료용으로 사용할 경우에는 동작 안되는 것이 있을 수 있으니 관련 Class를 수정해서 사용하면 될 것이다.


파일을 여러개로 나누어서 필요한 파일을 Load 하여 사용하는 방법으로 구현했다.

ㅇ 상대경로 자동 설정 : https://link2me.tistory.com/1197 참조

ㅇ MDB Layout 알아둘 사항 : https://link2me.tistory.com/1593 참조

ㅇ PHP Class 개념 이해 : https://link2me.tistory.com/1164 참조.

    PHP Class 함수는 스스로 작성해야 하며, 타 게시글을 찾다보면 이해하게 될 것으로 본다.

    게시판 구현에 필요한 대부분의 코드는 기록했지만 PHP Class 는 오픈하지 않았다.

    스스로 만들어야 할 영역이라고 보면 된다.

    DBDataClass.php 에 대한 사항은 https://link2me.tistory.com/1680 에 오픈했다.

ㅇ 페이징 처리 : https://link2me.tistory.com/1112 참조하되, bootstrap4 기반으로 Class 변경하는 건 직접 하시라.

    PHP Class 작성에 대한 일부 코드를 확인할 수 있다.


bbs.php 파일

<!DOCTYPE html>
<head>
<?php
require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php'; // 세션 체크
require_once $g['path_config'].'config.php';
require_once $g['path_layout'].'default/_import.head.php';
require_once $g['path_root'].'deviceChk.php';
?>
</head>

<body class="fixed-sn mdb-skin">
<header>
    <!-- Navbar -->
    <nav class="navbar fixed-top navbar-toggleable-md navbar-expand-lg scrolling-navbar double-nav">
        <div class="breadcrumb-dn mr-auto">
            <p><?=$hostName;?></p>
        </div>
        <ul class="nav navbar-nav nav-flex-icons ml-auto">
            <?php require_once $g['path_menu'].'item/item_login.php' ?>
        </ul>
    </nav>
    <!-- /.Navbar -->
</header>

<main>
    <div class="container-fluid text-center">
        <div class="row">
            <div class="col-md-12">
                <div class="content" id="panel_content">
                <!-- 불러온 파일이 이곳에 위치되도록 jQuery 처리 -->
                </div>
                <div id="ajaxPath" data-path="<?=$g['path_menu'];?>"></div>
            </div>
        </div>
    </div>
</main>
<!--/Main layout-->

<!-- SCRIPTS -->
<?php require_once $g['path_layout'].'default/_import.tail.php';?>
<script>
// SideNav Initialization
$(".button-collapse").sideNav();
new WOW().init();

var uri = (uri != null)? uri : "bbsList.php";
var datapath =$("#ajaxPath").attr('data-path');
var bbsid = (bbsid != null)? bbsid : "toadmin";

BBSListTable(uri,bbsid,1,'','',0);

$('.memberShow').on('click',function(e){
    e.preventDefault(); // a 링크, submit 실행 방지
    url = $(this).attr('href');
    var item = $(this).text();
    if(url != '#'){
        $('#panel_content').load(url, function(){
            ModifyData();
        });
    }
});

function fixedEncodeURIComponent (str) {
    // encodeURIComponent 함수는 IE8 이상의 브라우저에서 모두 지원한다.
    return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

function BBSListTable(uri,bbsid,curPage,where,keyword,idx){
    $('#panel_content').load(uri+'?bid='+bbsid+'&p='+curPage+'&where='+where+'&keyword='+fixedEncodeURIComponent(keyword)+'&uid='+idx, function() {
        //e.preventDefault();
        var curPage = $('#paging .act a').text();
        $('#paging li').click(function(e) {
            e.preventDefault();
            switch($(this).text()){
                case '◁':
                    curPage=parseInt($(this).next().text()) - 1;
                    break;
                case '▷':
                    curPage=parseInt($(this).prev().text()) + 1;
                    break;
                default:
                    curPage = $(this).text();
                    break;
            }
            BBSListTable(uri,bbsid,curPage,where,keyword,0);
        });

        $('#BBSListTable tbody tr').mouseover(function() {
            $(this).children().css({
                'backgroundColor' : '#DCDCDC', 'cursor' : 'pointer'
            });
        }).mouseout(function() {
            $(this).children().css({
                'backgroundColor' : '#FFFFFF', 'cursor' : 'default'
            });
        }).click(function() {
            var idx = $(this).attr('id');
            var bbsid =$("#bbsid").attr('data-bbsid');
            uri = "bbsView.php";
            BBSListTable(uri,bbsid,curPage,where,keyword,idx);
        });

        $('#BBSSearch').click(function(e){
            BBSSearch(uri,bbsid,curPage,where,keyword);
        });

        $('#BBSSearchKeyword').on('keypress', function(event){
            var agent = navigator.userAgent.toLowerCase();
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if(keycode == 13){ // 엔터키가 입력될 때까지는 어떤 것도 하지 않는다.
                event.preventDefault(); // 엔터키가 입력되면 현재 이벤트의 기본 동작을 중단한다.
                //event.stopPropagation(); // 현재 이벤트가 상위로 전파되지 않도록 중단한다.
                BBSSearch(uri,bbsid,curPage,where,keyword);
            }
        });

        $('#BBSHome').click(function(e){
            e.preventDefault();
            uri = "bbsList.php";
            BBSListTable(uri,bbsid,1,'','',0);
        });

        $('#bbsWrite').click(function(e){
            e.preventDefault();
            uri = $(this).attr('href');
            var bbsid =$("#bbsid").attr('data-bbsid');
            BBSListTable(uri,bbsid,curPage,where,keyword,0);
        });

        $('#bbsModify').click(function(e){
            e.preventDefault();
            uri = $(this).attr('href');
            var idx = $(this).attr('data-id');
            var page = $(this).attr('curPage');
            BBSListTable(uri,bbsid,page,where,keyword,idx);
        });

        $('#bbsRegister').click(function(){
            var subject = $('#subject');
            var content = $('textarea#content');
            var curPage = $('input[name=p]').val();

            if(subject.val() ==''){
                alert('제목을 입력하세요');
                subject.focus();
                return false;
            }

            if(content.val() ==''){
                alert('내용을 입력하세요');
                content.focus();
                return false;
            }

            $.ajax({
                url:datapath+'bbsWriteChk.php',
                type: 'POST',
                data: $("#bbswriteForm").serializeArray(),
                dataType:'text',
                success:function(msg){
                    if(msg == 1){
                        alert('등록했습니다.');
                        BBSListTable(uri,bbsid,curPage,where,keyword,idx);
                    } else if(msg == 2){
                        alert('수정했습니다.');
                        BBSListTable(uri,bbsid,curPage,where,keyword,idx);
                    } else if(msg==-2){
                        alert('수정권한이 없습니다.');
                    } else {
                        alert('데이터를 다시 한번 확인하세요\n'+msg);
                        return false;
                    }
                },
                error: function(jqXHR, textStatus, errorThrown){
                    alert("arjax error : " + textStatus + "\n" + errorThrown);
                }
            });

        });

        $('#bbsDelete').click(function(e){
            e.preventDefault();
            var idx = $(this).attr('data-id');
            var page = $(this).attr('curPage');
            BBSDelete(uri,bbsid,page,where,keyword,idx);
        });

        $('#comment_form').click(function(e){
            e.preventDefault();
            var comment = $("input[name=comment]");
            if(comment.val() ==''){
                alert('댓글을 입력하세요');
                comment.focus();
                return false;
            }
            var page = $("input[name=p]").val();
            var uid = $("input[name=parentid]").val();

            $.ajax({
                url:datapath+'bbsCommentChk.php',
                type: 'POST',
                data: {
                    mode:$("input[name=mode]").val(),
                    parentid:uid,
                    userID:$("input[name=userID]").val(),
                    userNM:$("input[name=userNM]").val(),
                    comment:$("input[name=comment]").val()
                    },
                dataType:'text',
                success:function(msg){
                    if(msg == 1){
                        alert('등록했습니다.');
                        uri = "bbsView.php";
                        BBSListTable(uri,bbsid,page,where,keyword,uid);
                    } else if(msg==-2){
                        alert('수정권한이 없습니다.');
                        return false;
                    } else {
                        alert('데이터를 다시 한번 확인하세요\n'+msg);
                        return false;
                    }
                },
                error: function(jqXHR, textStatus, errorThrown){
                    alert("arjax error : " + textStatus + "\n" + errorThrown);
                }
            });

        });

        $(".comment_del").click(function(){
            var idx = $(this).parent().parent().attr('id');
            var page = $("input[name=p]").val();
            CommnetDelete(uri,bbsid,page,where,keyword,idx);
        });

        $('#ToMainPage').click(function(){
            window.location.href = $(location).attr('protocol')+"//"+$(location).attr('host');
        });

    });
}

function BBSSearch(uri,bbsid,curPage,where,keyword){
    var where = $('[name=where]').val();
    var keyword = $('[name=keyword]').val();
    if(keyword.length == 0){
        alert('검색어를 입력하세요');
        $('input[name=keyword]').focus();
        return false;
    }
    BBSListTable(uri,bbsid,1,where,keyword,0);
}

function BBSDelete(uri,bbsid,curPage,where,keyword,idx){
    var verify = confirm('삭제하시겠습니까? \n 복구할 수 없습니다.');
    if (verify) {
        $.get('bbsDelete.php?idx='+idx, function(msg) {
            if (msg == 1) {
                alert('삭제되었습니다.');
                uri = "bbsList.php";
                BBSListTable(uri,bbsid,curPage,where,keyword,0);
            } else if(msg == -2){
                alert('삭제 권한이 없습니다.');
            } else {
                alert('삭제중 오류가 발생하였습니다.\n'+msg); // 디버깅 모드
                //alert('삭제중 오류가 발생하였습니다.'); // 운용 모드
            }
        });
    }
}

function CommnetDelete(uri,bbsid,curPage,where,keyword,idx){
    var verify = confirm('삭제하시겠습니까? \n 복구할 수 없습니다.');
    if (verify) {
        $.get('bbsCommentDelete.php?idx='+idx, function(msg) {
            if (msg == 1) {
                uri = "bbsView.php";
                var uid = $("input[name=parentid]").val();
                BBSListTable(uri,bbsid,curPage,where,keyword,uid);
            } else if(msg == -2){
                alert('삭제 권한이 없습니다.');
            } else {
                alert('삭제중 오류가 발생하였습니다.\n'+msg);
                //alert('삭제중 오류가 발생하였습니다.');
            }
        });
    }
}
</script>
</body>
</html>

<?php

// 파일명 : bbsList.php

error_reporting(0);
// 테이블 접속 처리
require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php';
require_once $g['path_root'].'deviceChk.php';
if($mtype == 3){
    require_once $g['path_root'].'ipFiltering.php';
}
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'dbDataClass.php';
require_once $g['path_class'].'bbsClass.php';
require_once $g['path_class'].'adminClass.php';
$a = new adminClass();
$b = new bbsClass();
$d = new DBDataClass(); // AES_Decode()

$bbsid = isset($_GET['bid']) ? $_GET['bid'] :'toadmin';
$link_url = "bbs.php"; // 현재 실행중인 파일명 가져오기
$page = isset($_GET['page'])? trim($_GET['page']):1;//페이지 변수 설정
$rowsPage = ($mtype == 3) ? 5 : 5; // 한 화면에 표시되는 게시글 수
$curPage = isset($_GET['p']) ? $_GET['p'] : 1;
$m = isset($_GET['m']) ? $_GET['m'] :'list';

$flddata ="*";// 화면에 출력할 칼럼 발췌
$where = isset($_GET['where']) ? $_GET['where']: '';
$keyword = isset($_GET['keyword']) ? $_GET['keyword']: '';
$xorderby= isset($xorderby) ? $xorderby : 'uid DESC'; // 없는 칼럼인지 꼭 체크하라.

$sqlque = 'display=1';
$uri =isset($_GET['uri'])? $_GET['uri']:'';

if($where && $keyword) {
    if($where == 'subject') $sqlque .= " and (subject LIKE '%".$keyword."%') ";
    if($where == 'userNM') $sqlque .= " and (userNM LIKE '%".$keyword."%') ";
}

$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 ='bbs_data'; // 기본 접속 테이블과 동일구조 테이블 처리
$NUM = $d->getDbRows($table,$sqlque); // 전체 게시글수
$TPG = $b->getTotalPage($NUM,$rowsPage);
$rows= $d->getDbArray($table,$sqlque,$flddata,$xorderby,$rowsPage,$curPage);
$i = 0;
?>
<div class="table-responsive text-nowrap">
<div class="float-left">
    <?php if( $keyword ):?><strong>"<?php echo $keyword?>"</strong> 검색결과 : <?php endif?>
    <?php echo number_format($NUM)?>개 (<?php echo $curPage;?>/<?php echo $TPG;?>페이지)
</div>
<div class="float-right">
    <?php if(isset($_SESSION['userID'])):?>
    <a href="bbsWrite.php" class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 " id="bbsWrite">글쓰기</a>
    <?php endif?>
    <div id="bbsid" data-bbsid="<?php echo $bbsid; ?>"></div>
</div>

<table id="BBSListTable" class="table table-striped table-bordered table-hover table-sm" cellspacing="0" width="100%">
    <thead align='center'>
        <tr>
            <?php if($mtype==3):?><th scope="col">No</th><?php endif;?>
            <th scope="col">제목</th>
            <?php if($mtype==3):?><th scope="col">이름</th><?php endif;?>
            <th scope="col">날짜</th>
            <?php if($mtype==3):?><th scope="col">조회수</th><?php endif;?>
        </tr>
    </thead>
    <tbody>
        <?php if($NUM == 0):?>
        <tr>
            <td colspan="5">등록된 게시글이 없습니다.</td>
        </tr>
        <?php else:?>
        <?php foreach($rows as $R):?>
        <?php
            $no = $NUM - (($curPage - 1) * $rowsPage) - $i;
            $i++;
        ?>
        <tr id="<?php echo $R['uid']; ?>">
            <?php if($mtype==3):?><td><?php echo $no;?></td><?php endif;?>
            <td class="text-left"><?php echo $R['subject'];?></td>
            <?php if($mtype==3):?><td><?php echo $R['userNM'];?></td><?php endif;?>
            <td><?php echo substr($R['d_regis'],0,8);?></td>
            <?php if($mtype==3):?><td><?php echo $R['hit'];?></td><?php endif;?>
        </tr>
        <?php endforeach;?>
        <?php endif;?>
    </tbody>
</table>
<div class='form-group'>
    <form name="BBSForm" class="form-inline" action="<?php echo $link_url;?>">
        <input type="hidden" name="m" value="<?php echo $m;?>" />
        <input type="hidden" name="orderby" value="<?php echo $xorderby;?>" />

        <div class="input-group mb-3" style="width:80px;">
            <select name="where" class="browser-default custom-select">
                <option value="subject">제목</option>
                <option value="userNM">등록자</option>
            </select>
        </div>
        <div class="input-group mb-3" style="width:calc(100% - 80px);">
          <input type="text" name="keyword" class="form-control" id="BBSSearchKeyword">
          <div class="input-group-append">
            <button class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" type="button" id="BBSSearch">검색</button>
            <button class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" type="button" id="BBSHome">목록</button>
          </div>
        </div>
    </form>
</div>
<?php $b->PageLinkView($link_url,$NUM,$rowsPage,$curPage,$g['url_link']);?>
<button class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0" id="ToMainPage" type="button">메인화면 전환</button>
</div>

<?php

// 파일명 : bbsView.php

error_reporting(0);
// error_reporting(E_ALL); 
//ini_set("display_errors", 1);

require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php';
require_once $g['path_root'].'deviceChk.php';
if($mtype == 3){
    require_once $g['path_root'].'ipFiltering.php';
}
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'dbDataClass.php';
require_once $g['path_class'].'bbsClass.php';
$c = new bbsClass();
$d = new DBDataClass();

$bid = isset($_GET['bid']) ? $_GET['bid']: '';
$curPage = isset($_GET['p']) ? $_GET['p'] : 1;

$R = $d->getDbData('bbs_data', 'uid='.$_GET['uid'], '*');
$html = ($R['html'] == 1) ? 'HTML' : 'TEXT';
?>
<table class="table table-bordered table-hover table-sm" cellspacing="0" width="100%">
    <tr>
        <td style="width:70px;">제목</td>
        <td class="text-left"><?php echo $R['subject']?></td>
    </tr>
    <tr>
        <td>내용</td>
        <td class="text-left"><?php echo $c->getContents($R['content'],$html);?></td>
    </tr>
</table>

<?php include_once $g['path_bbs'].'bbsComment.php';?>

<div class="table-responsive text-nowrap">
    <div class="float-left info">
        <button class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" type="button" id="BBSHome">목록</button>
    </div>
    <div class="float-right info">
        <?php if($R['userID'] == $_SESSION['userID']):?>
        <a href="bbsWrite.php" class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" id="bbsModify" data-id="<?=$R['uid'];?>" curPage="<?=$curPage;?>">수정</a>
        <?php endif;?>
        <?php if($R['userID'] == $_SESSION['userID'] || (isset($_SESSION['authID']) && $_SESSION['authID']==1) ):?>
        <button class="btn btn-md btn-outline-default m-0 px-3 py-2 z-depth-0 waves-effect" type="button" id="bbsDelete" data-id="<?=$R['uid'];?>" curPage="<?=$curPage;?>">삭제</button>
        <?php endif;?>
    </div>
</div>

<?php

// 파일명 : bbsWrite.php

error_reporting(0);
// 테이블 접속 처리
require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php';
require_once $g['path_root'].'deviceChk.php';
if($mtype == 3){
    require_once $g['path_root'].'ipFiltering.php';
}
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'dbDataClass.php';
require_once $g['path_class'].'bbsClass.php';
require_once $g['path_class'].'adminClass.php';
$a = new adminClass();
$b = new bbsClass();
$d = new DBDataClass(); // AES_Decode()

$bid = isset($_GET['bid']) ? $_GET['bid']: '';
$uid = isset($_GET['uid']) ? $_GET['uid']: '';
$curPage = isset($_GET['p']) ? $_GET['p'] : 1;
$R=$d->getUidData('bbs_data',$uid);

?>
<div class="table-responsive text-nowrap">
<form id="bbswriteForm" method="post" class="text-center border border-light p-5">
    <table class="table table-striped table-bordered table-hover table-sm" cellspacing="0" width="100%">
        <input type="hidden" name="mode" value="write" />
        <input type="hidden" name="p" value="<?php echo $curPage;?>" />
        <input type="hidden" name="bid" value="<?php echo $bid;?>" />
        <input type="hidden" name="uid" value="<?php echo $R['uid'];?>" />
        <input type="hidden" name="userID" value="<?php echo $_SESSION['userID'];?>" />
        <input type="hidden" name="userNM" value="<?php echo $_SESSION['userNM'];?>" />

        <tr>
            <td>제목</td>
            <td><input type="text" name="subject" id="subject" class="form-control mb-4" placeholder="제목을 입력하세요" value="<?=$R['subject'];?>"></td>
        </tr>

        <tr>
            <td>내용</td>
            <td><textarea name="content" id="content" class="form-control mb-4" rows="8"  placeholder="내용을 입력하세요"><?=$R['content'];?></textarea></td>
        </tr>

        <tr>
            <td colspan="2">
            <button class="btn btn-info btn-block my-4" id="bbsRegister" type="submit">등록</button>
            </td>
        </tr>
    </table>
</form>
</div>


블로그 이미지

Link2Me

,
728x90

게시판 테이블 샘플이다.


CREATE TABLE IF NOT EXISTS `bbs_data` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `display` tinyint(2) NOT NULL DEFAULT '1',
  `bbsid` varchar(30) NOT NULL DEFAULT '',
  `level` tinyint(4) NOT NULL DEFAULT '1',
  `subject` varchar(200) NOT NULL DEFAULT '',
  `content` text NOT NULL,
  `html` tinyint(2) NOT NULL DEFAULT '0',
  `depth` tinyint(4) NOT NULL DEFAULT '0',
  `d_regis` varchar(14) NOT NULL DEFAULT '',
  `d_modify` varchar(14) NOT NULL DEFAULT '',
  `hit` int(11) NOT NULL DEFAULT '0',
  `hidden` tinyint(4) NOT NULL DEFAULT '0',
  `notice` tinyint(4) NOT NULL DEFAULT '0',
  `userID` varchar(60) NOT NULL,
  `userNM` varchar(50) NOT NULL,
  `ip` varchar(25) NOT NULL DEFAULT '',
  PRIMARY KEY (`uid`),
  KEY `bbsid` (`bbsid`),
  KEY `subject` (`subject`),
  KEY `userID` (`userID`),
  KEY `d_regis` (`d_regis`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;



댓글 게시판 테이블


CREATE TABLE IF NOT EXISTS `bbs_comment` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `parentid` int(11) NOT NULL DEFAULT '0',
  `comment` varchar(255) NOT NULL DEFAULT '',
  `d_regis` varchar(14) NOT NULL DEFAULT '',
  `userID` varchar(50) NOT NULL DEFAULT '',
  `userNM` varchar(50) NOT NULL,
  `ip` varchar(25) NOT NULL DEFAULT '',
  PRIMARY KEY (`uid`),
  KEY `parent_uid` (`parentid`),
  KEY `d_regis` (`d_regis`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


블로그 이미지

Link2Me

,
728x90

일반적으로 HTML5 에서는 아래와 같이 테이블 체크박스를 만들어주면 된다.

<table>
    <thead>
        <tr>
            <th><input type="checkbox" id="chkall" /></th>
            <th>성명</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            <td>홍길동</td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>이상철</td>
        </tr>
    </tbody>
</table>

 

하지만 MDB에서는 이렇게 하면 동작 자체가 안된다.

아래와 같은 형식으로 구현해야 코드가 동작한다.

<table>
    <thead>
        <tr>
            <th>
            <th scope="col">
                <div class="form-check form-check-inline">
                <input type="checkbox" class="form-check-input" id="checkall">
                <label class="form-check-label" for="checkall"></label>
                </div>
            </th>
            </th>
            <th>성명</th>
        </tr>
    </thead>
    <tbody>
        <?php $i=0; while($R = mysql_fetch_array($RCD)):?>
        <tr>
            <td>
                <div class="form-check form-check-inline">
                <input type="checkbox" class="form-check-input" name="uid[]" id="<?php echo $R['uid'];?>" value="<?php echo $R['uid'];?>">
                <label class="form-check-label" for="<?php echo $R['uid'];?>"></label>
                </div>
            </td>
            <td><?php echo $R['name'];?></td>
        </tr>
        <?php $i++; endwhile;?>
    </tbody>
</table>

 

$i=0;
while($R = mysqli_fetch_array($result)){
	$i++;
	if(in_array($R['id'],$cat3Array)){ 
		echo'<div class="form-check form-check-inline">
			  <input type="checkbox" class="form-check-input" name="cat3[]" id="'.$R['id'].'" value="'.$R['id'].'" checked>
			  <label class="form-check-label" for="'.$R['id'].'">'.$R['name'].'</label>
			</div>';
	} else {
		echo'<div class="form-check form-check-inline">
			  <input type="checkbox" class="form-check-input" name="cat3[]" id="'.$R['id'].'" value="'.$R['id'].'">
			  <label class="form-check-label" for="'.$R['id'].'">'.$R['name'].'</label>
			</div>';
	}
	if($i % 3 == 0) {echo '<br />';}
}

 

필요할 때만 구현하다보니검색하고 사용법을 익히는 시간 낭비를 하게 되어 적어둔다.

블로그 이미지

Link2Me

,