MySQL 컬럼 순서 바꾸기

SQL 2016. 12. 10. 07:46

MySQL 테이블 구조 이해도를 높이기 위해서 칼럼 순서를 바꿀 필요가 있어서 변경했다.

treeview 테이블이다.

 

 

ALTER TABLE 테이블명 MODIFY COLUMN 컬럼명 자료형 AFTER 다른컬럼;
alter table treeview modify column parent_id varchar(11) after id;

 

칼럼의 위치가 변경된 것을 확인할 수 있다.

 

alter table members modify column mfoneNO varchar(16) after phoneSE;
alter table members modify column userNM varchar(16) after userID;

728x90
블로그 이미지

Link2Me

,

MySQL DB와의 연동하여 통계 그래프를 작성하는 샘플이다.

100% PHP 코드함수까지 오픈하지 않는다. 하지만 핵심적으로 알아야 할 내용은 모두 작성했다.

var line1 = [<?php echo $data;?>];  PHP 문자열을 이렇게 대입해주면 자바스크립트에서 배열 변수로 인식하기 때문에 ajax response 메시지 값도 [jsonObj.data] 로 해주면 되는줄 알고 alert 창으로 확인하면서 시간낭비를 많이 했다. alert 창 메시지를 육안으로 확인하면 PHP 변수를 배열화한 것과 다를바가 없었다. typeof 를 찍어보고 나서 문제가 뭔지 찾아내고 바로 해결했다. 기초가 약해서 발생한 문제였다.


<?php
require_once 'connect.php'; // db접속 성공
require_once 'phpclass/statsClass.php'; // 통계 클래스
$b = new statsClass;
$R = $b->extract_YM(); // DB에서 년월 추출

$ym = date("Ym"); // 현재 년월

$ticks = $b->maxday_YM($ym);  // X축 좌표 값
$data = $b->dailyCnt_value($ym);  // 막대그래프 값
?>
<!DOCTYPE html>
<head>
<meta charset=UTF-8" />
<meta name="robots" content="noindex,nofollow"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
<meta http-equiv="X-UA Compatible" control="IE=edge,chrome=1" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<!-- http://www.jqplot.com 제공 자바스크립트 include -->
<script type="text/javascript" src="./plugin/jqplot/jquery.jqplot.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.barRenderer.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.pointLabels.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.canvasAxisTickRenderer.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.categoryAxisRenderer.js"></script>
<link rel="stylesheet" type="text/css" href="./plugin/jqplot/jquery.jqplot.css" />
<script type="text/javascript">
$(document).ready(function(){
    var plot1;
    var line1 = [<?php echo $data;?>];
    //var line2 = [10, 8, 22, 15, 10];  // 막대그래프를 2개 그리고자 할 경우
    var xAxis = [<?php echo $ticks;?>];

    renderChart(line1,xAxis);

    $('#selectmonth').on('change',function(){
        if(this.value !== ""){
            var optVal=$(this).find(":selected").val();
            //var year = optVal.substr(0,4); // 년
            //var month = optVal.substr(4,2); // 월
            $.post('ajaxdb.php',{optVal:optVal},function(msg){
                //alert(msg); // 배열 형태로 넘어오는지 확인 목적
                var jsonObj = $.parseJSON(msg); // JSON 문자열을 JavaScript object 로 반환
                //alert(typeof jsonObj.data); // string
                data = jsonObj.data.split(','); // 문자열을 배열로 변환
                xAxis = jsonObj.ticks.split(',');
                //alert(typeof data);
                updatePlot(data,xAxis);
            });
        }
    });

});

function renderChart(data,xAxis){
    plot1 = $.jqplot('chartDiv', [data], CreateBarChartOptions(xAxis));
}

function updatePlot(data,xAxis){
    plot1.destroy();
    plot1 = $.jqplot('chartDiv', [data], CreateBarChartOptions(xAxis));
}

function CreateBarChartOptions(xAxis) {
    var optionsObj = {
        title: '일자별 접속 통계',
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer, // 막대 그래프
            rendererOptions: { barWidth: 15 }, // bar의 너비 수동으로 설정
            pointLabels: { show: true } // 레이블 값
        },
        axes: {
            xaxis: {
                renderer: $.jqplot.CategoryAxisRenderer,
                ticks: xAxis,
                tickOptions: {
                    formatString: '%d' // 정수형으로 표시
                }
                //label:'일자'
            }
        },
        highlighter: { show: false }
    };
    return optionsObj;
}

</script>

</head>
<body>
<div id="chartDiv" style="height:300px;width:900px;"></div>
<div style="height:300px;width:890px;margin-top:10px;text-align:right;">
<select name="month" id="selectmonth">
<option value="">년월 선택</option>
<?php
    while ($row = mysqli_fetch_array($R)){
        echo "<option value='".$row[0]."' ";
        echo ">".$row[0]."</option>\n";
    }
?>
</select>
</div>
</body>
</html>


==== ajaxdb.php ====

<?php
if(isset($_POST['optVal'])){
    require_once 'connect.php'; // db접속 성공
    require_once 'phpclass/statsClass.php'; // 통계 클래스
    $b = new statsClass;
    $ym = $_POST['optVal'];
    $data = $b->dailyCnt_value($ym); // 문자열로 받음
    $ticks = $b->maxday_YM($ym); // 문자열로 받음
    $R = array('data'=>$data, 'ticks'=>$ticks); // X축 좌표값과 일별 통계 값을 DB에서 추출하여 배열화 처리
    echo json_encode($R);
}
?>


alert(typeof jsonObj.data); 으로 type 을 확인해서 object 인지 string 인지 확인하여 상황에 맞게 변환해서 사용하는케 키포인트다.


json_encode 를 사용하면 배열로 결과를 반환하는 걸 자유자재로 할 수 있다.

어떻게 하는지는 바로 위의 코드를 보면 알 수 있으므로 이걸 본 방문객은 쉽게 해결이 가능하리라 본다.

구글 검색과 jqplot 검색을 하면 그래프 그려주는 js 파일 구조에 대해 파악이 될 것이다.

728x90
블로그 이미지

Link2Me

,

MySQL DB와의 연동하여 통계 그래프를 작성하는 방법이다.

바로 앞 게시물(http://link2me.tistory.com/1132)과 비교해서 달라진 부분이 어떤 것인지만 비교해보면 된다.

색깔을 표시한 부분을 주의깊게 살펴보면 답은 의외로 간단하다.


<?php
//require_once 'connect.php'; // db접속 성공
//require_once 'phpclass/boardClass.php'; // 게시판 클래스
$line1 ="4,6,2,5";  // DB와 연동한 결과로 문자열을 생성했다고 가정한다.
?>
<!DOCTYPE html>
<head>
<meta charset=UTF-8" />
<meta name="robots" content="noindex,nofollow"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
<meta http-equiv="X-UA Compatible" control="IE=edge,chrome=1" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<!-- http://www.jqplot.com 제공 자바스크립트 include -->
<script type="text/javascript" src="./plugin/jqplot/jquery.jqplot.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.barRenderer.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.pointLabels.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.categoryAxisRenderer.js"></script>
<link rel="stylesheet" type="text/css" href="./plugin/jqplot/jquery.jqplot.css" />
<script type="text/javascript">
$(document).ready(function(){
    var line1 = [<?php echo $line1;?>];
    var line2 = [10, 8, 22, 15, 10];
    var ticks = ['닛산', '포르쉐', 'KIA', '현대', '벤츠'];
 
    $('#chart1').jqplot([line1,line2], {
        title:'막대그래프 예제',
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer, // 막대 그래프
            rendererOptions: { barWidth: 25 }, // bar의 너비 수동으로 설정
            pointLabels: { show: true, formatString: '%d' } // 레이블 값
        },
        axes:{
            xaxis:{
                renderer: $.jqplot.CategoryAxisRenderer,
                ticks: ticks // X축 값
            }
        }
    });
});
</script>

</head>
<body>
<div id="chart1" style="height:300px;width:600px; "></div>
</body>
</html>


다음 기회에 월을 선택하면 일별 막대그래프를 자동으로 그려주는 통계에 대한 PHP코드를 작성해볼 생각이다.

로직은 년월에 대한 값을 DB에서 자동으로 선택해서 selectbox에 표시하고 선택한 년월 정보로 통계그래프가 표시되도록 하면 된다.

- DB에서 년월에 대한 값을 중복없이 뽑아낸다.

- 년월을 선택하면 마지막 일자의 값을 자동으로 추출해서 문자열을 생성한다.

- jQuery change 로 해당 값이 변동되면 그래프를 그리도록 한다.

728x90
블로그 이미지

Link2Me

,

시각적으로 통계 결과를 화면에 보여주는 걸 구현할 때 jqplot 플러그인을 이용하면 쉽게 챠트를 그릴 수 있다.


위와 같은 막대 그래프로 통계 결과를 보여주고자 한다면 어떻게 해야 할까?


1. http://www.jqplot.com 사이트에서 플러그인 파일을 다운로드하여 서버에 설치한다.

   현재 기준 최신버전은 jquery.jqplot.1.0.9.d96a669.zip 이다.

   이 사이트를 알게 된 것은 2년전에 전문 개발자를 통해 알았는데 jQuery를 배우니 쉽게 활용이 가능하다.


2. 다운로드한 파일에 usage.txt 파일에 사용법이 나온다.

    그리고 웹사이트 Examples 에도 다양한 형태의 예제 파일이 있다.

    하지만 설명이 잘 이해되지 않을 수도 있다.


3. 간략하게 예제를 살펴보자.

    예제는 DB와의 연동까지는 고려하지 않은 1단계라고 보면 된다.

    필요한 플러그인 js 파일이 있는 경로명을 제대로 표시해주어야 그래프가 그려진다.

    - 변수 line1 과 line2 두개를 표시하고자 할 경우이며, 1개만 표시하고 싶으면 line1 만 적어준다.

    - 변수 ticks 는 X 좌표에 해당되는 값을 표시

    - title : 상단 제목


<!DOCTYPE html>
<head>
<meta charset=UTF-8" />
<meta name="robots" content="noindex,nofollow"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
<meta http-equiv="X-UA Compatible" control="IE=edge,chrome=1" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<!-- http://www.jqplot.com 제공 자바스크립트 include -->
<script type="text/javascript" src="./plugin/jqplot/jquery.jqplot.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.barRenderer.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.pointLabels.js"></script>
<script type="text/javascript" src="./plugin/jqplot/plugins/jqplot.categoryAxisRenderer.js"></script>
<link rel="stylesheet" type="text/css" href="./plugin/jqplot/jquery.jqplot.css" />
<script type="text/javascript">
$(document).ready(function(){
    var line1 = [4, 6, 2, 5];
    var line2 = [10, 8, 22, 15, 10];
    var ticks = ['닛산', '포르쉐', 'KIA', '현대', '벤츠'];
 
    $('#chart1').jqplot([line1,line2], {
        title:'막대그래프 예제',
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer,
            rendererOptions: { barWidth: 25 },
            pointLabels: { show: true, formatString: '%d' }
        },
        axes:{
            xaxis:{
                renderer: $.jqplot.CategoryAxisRenderer,
                ticks: ticks
            }
        }
    });
});
</script>

</head>
<body>
<div id="chart1" style="height:300px;width:600px; "></div>
</body>
</html>


보는 바와 같이 코드는 정말 심플하다.


변수 값을 PHP 와 연동하여 처리하는 것은 다음에 기술할 예정이다.

통계 그래프에 직접 변수를 지정해주는 경우는 거의 없을 것이고, DB와 연동하여 실시간처리가 되도록 해야 의미가 있을 것이다.


설명이 잘된 사이트가 있어서 링크를 걸어둔다.

http://wickedmagic.tistory.com/525


jqplot.com 사이트에서 영문으로 된 자료를 가지고 약간만 테스트를 하면서 본인이 원하는 스타일로 구현하면 된다. 그리고 좀 더 세부적인 내용을 알고자 한다면 구글에서 jqplot bar width example 와 같은 검색어를 입력하면 원하는 자료를 쉽게 찾을 수 있다.

http://www.jqplot.com/docs/files/plugins/jqplot-barRenderer-js.html 에도 옵션에 대한 설명이 나온다.

728x90
블로그 이미지

Link2Me

,

MP3 Player jQuery 화면 만들기 예제를 적어둔다.

실제 사용은 안하고 있으나, 화면 생성에 대한 사항을 사용할 일이 있을때 참고하려고 적어둔다.

좋은 MP3 플레이어 jQuery 는 http://www.wimpyplayer.com/ 다.


<div id="mp3playerdiv"></div>
<!--플레이어-->
<div class="player">
<div class="player_bg"><!--tmp--></div>
<div class="player_area" id="tubeplayer"></div>
</div>
<!--플레이어-->

<script type="text/javascript">
//<![CDATA[
   //플레이어
   $('.simbol a').click(function(e) {
   e.preventDefault();
   $(".player").fadeIn();
  
     $("#tubeplayer").append('<iframe width="400" height="80" src="<?php echo $g['dir_module_skin']?>movie/demo/movie.php?file='+this.id+'" frameborder="0" scrolling="no" allowfullscreen></iframe>');
  
      var temp = $('.player_area');
   
       if (temp.outerHeight() < $(document).height() ) temp.css('margin-top', '-'+temp.outerHeight()/2+'px');
       else temp.css('top', '0px');
       if (temp.outerWidth() < $(document).width() ) temp.css('margin-left', '-'+temp.outerWidth()/2+'px');
       else temp.css('left', '0px');

      $(".player .player_bg").on("click", function() {
      $(".player").fadeOut();
      $("#tubeplayer iframe").remove();
    });
           
      //키보드 esc
      $(document).bind('keydown', function(e) {
        if (e.which == 27) {
        $(".player").fadeOut();
        $("#tubeplayer iframe").remove();
        }
      });

    });
    //플레이어

//]]>
</script>

728x90
블로그 이미지

Link2Me

,