만들면서 배우는 CodeIgniter Q&A

제목 세그먼트 관련 문제입니다.
글쓴이 유후~ 작성시각 2017/01/13 11:03:04
댓글 : 4 추천 : 0 스크랩 : 1 조회수 : 15188   RSS

게시판 만들기에서 처음 차근차근 진행 하다가 잘안돼는 부분은 게시판 참조 해가면 만들고 있습니다.

그러다 코드가 좀 엉킨것 같아 다시 하고 다시 해서 어느정도 해결에 해결을 하고 있던 차에 

세그먼트부분에서 문제가 생겼네요

4.7 전체코드까지 훌트면서 혹시모를 오탈자를  방지하기위해 노력 했지만

왜 segment(7)부분에서 문제가 되는지 알수가 없네요

page부분이 추가 되지 않는다는걸 확인 하고

 data['page'] = $page = ...... 부분 적용하고, list_v.php에 /page/<?php echo $page;?> 추가후

목록에서 view로 들어가면 segment(7)부분이 %20%20%20%20%20%20....page번호 로 나타 납니다.

그런 후 다시 목록으로이동 하면 

A Database Error Occurred

Error Number: 1064

you have an error in your SQL sytax; check the manual that corresponds to your MySQL server version for the right syntax to 

use near '-5, 5' at line 1

SELECT * FROM ci_board ORDER BY board_id DESC LIMIT -5, 5

 

에러가 발생 됩니다.

segment(7)을 가져올때 urldecode()합수를 함께 가져오는 것 같은데

검색어가 있을 경우 'q' 에의해서 urldecode()합수가 적용 되어야 되고, page가 있을경우

url_explode()함수에 의해 세그먼트 숫자를 적용 받는게 아닌가 싶은데 좀 어렵네요 ^^

 

 

 

 다음글 todo css 관련질문입니다. (1)
 이전글 A Database Error Occurred (94p... (2)

댓글

변종원(웅파) / 2017/01/13 13:04:32 / 추천 0
목록의 주소 올려주세요. 7번째 세그먼트가 어찌 되는지 알면 답을 찾으실 수 있습니다.
유후~ / 2017/01/13 13:52:19 / 추천 0

 list_v.php에서 뷰로 이동 시 

<article id="board_area">
  <header>
    <h1></h1>
  </header>
    <h1></h1>
      <table cellpadding="0" cellspacing="0">
        <thead>
          <tr>
            <th scope="col">번호</th>
            <th scope="col">제목</th>
            <th scope="col">작성자</th>
            <th scope="col">조회수</th>
            <th scope="col">작성일</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($list as $lt){
        
        ?>
          <tr>
            <th scope="row"><?php echo $lt->board_id; ?></th>
            <td><a rel="external" href="/bbs/<?php echo $this->uri->segment(1); ?>/view/<?php echo $this->uri->segment(3); ?>/board_id/<?php echo $lt->board_id; ?>/page/
            <?php echo $page; ?>"><?php echo $lt->subject; ?></a>
 </td>
            <td><?php echo $lt->user_name; ?></td>
            <td><?php echo $lt->hits; ?></td>
            <td>
            <time datetime="<?php echo mdate("%Y-%M-%J", human_to_unix($lt->reg_date)); ?>">
            <?php echo mdate("%Y-%M-%J", human_to_unix($lt->reg_date)); ?></time>
            </td>
          </tr>
          <?php } ?>
        </tbody>
        <tfoot>
          <tr>
            <th colspan="5"><?php echo $pagination; ?></th>
          </tr>
        </tfoot>
      </table> 
      <div>
        <form id="bd_search" method="post">
          <input type="text" name="search_word" id="q" onkeypress="board_search_enter(document.q);" />
          <input type="button" value="검색" id="search_btn">
        </form>
      </div> 
</article>

view에서는 page값은 넘어오지 않습니다. 그리고 segment(7) 확인 하니깐 %20%20%20%20%20%20%20%20%20%20%20%201  <- 1이 segment(7)인것 같은데요 왜 붙어서 오는지 그것도 list_v.php에서 view로 넘어가면서 딸려 드러갑니다.

그리고 원래 $page값이 같이 않넘어 가나요? view 에서 echo $page 값이 없네요

list페이지에서는 echo $page 했보면 페이지 숫자 나오고 있습니다. 

참고로 board.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Board extends CI_Controller {
  
  function __construct(){
    
    parent::__construct();
    
    $this -> load -> database();
    
    $this -> load -> model('board_m');
    
    $this -> load -> helper(array('url', 'date'));
    
    }
  
  public function index(){
    
    $this->lists();
    
    }
  
  public function _remap($method){
    
    //헤더 include
    $this->load->view('header_v');
    
    if(method_exists($this, $method)){
      $this->{"{$method}"}();
      }
    
    $this->load->view('footer_v');
    
    
    }
    
    /**
    목록 불러오기
    **/
  public function lists(){
    
    
    $this->load->helper('alert'); 
    
    $this->output->enable_profiler(true);
    //검색어 초기화
    $search_word = $page_url = '';  //list_v.php form 에서 input text부분 -> $search_word
    // 주소중에서 q(검색어) 세그먼트가 있는지 검사 하기위해 주소를 배열로 반환('/'를 기준으로)
    
    $uri_segment = 5;
    
    $uri_array = $this->segment_explode($this->uri->uri_string());
    
    if(in_array('q', $uri_array)){ //$uri_array변수중에 q가 있는지(즉 주소에 검색어가있는지)
     // 주소에 검색어가 있으면
     $search_word = urldecode($this->url_explode($uri_array, 'q'));  //검색어를 디코딩함
     
     //페이지네이션 용 주소
     $page_url = '/q/' .$search_word;
     
     $uri_segment = 7; //검색어가 들어갔을때의 $uri_segment를 7로 한다.
      }
 
    
    // 페이지네이션부분
    $this->load->library('pagination');
    //라이브러리에서 pagination.php불러오기
    $config['base_url'] = '/bbs/board/lists/ci_board/'.$page_url.'/page/';
    //주소로 보는 segment숫자 : board[1]/lists[2]/ci_board[3]/page[4]/숫자[5] 
    $config['total_rows'] = $this->board_m->get_list($this->uri->segment(3), 'count', '', '', $search_word);
    //count함수를 통해 num_row()값을 받음, segment(3)은 테이블 명이 됨
    $config['per_page'] = 5;
    //한페이지에 표시할 게시물 수
    $config['uri_segment'] = $uri_segment;
    //페이지번호가 위치한 세그먼트(5전째 segment에 페이지 번호가 들어감 즉 /bbs/board/lists/ci_board/page/페이지번호)
    $this->pagination->initialize($config);
    //페이지네이션 초기화
    
    $data['pagination'] = $this->pagination->create_links();  //결국 이 link통해 id값전달됨
    //페이지링크 생성 view에서 사용할 변수에 할당
    
    $data['page'] = $page = $this->uri->segment($uri_segment, 1);
    //게시물 목록을 불러오기위한 offset, limit 값 가져오기 
    //alert($page);
    if($page > 1){  //변수$page가 1보다크면 즉 2번째이상 page이면
      
      $start = (($page / $config['per_page'])) * $config['per_page'];
      
      }else{
      
      $start = ($page - 1) * $config['per_page'];
      }
      
      $limit = $config['per_page'];
      
    $data['list'] = $this->board_m->get_list($this->uri->segment(3), '', $start, $limit, $search_word);
    $this->load->view('board/list_v', $data);
    }
    
   
      /**
      게시물 보기
      **/
      
      function view(){
        //게시판이름과 게시물 번호에 해당하는 게시물 가져오기 - model에서 return 값을 받음
        $data['views'] = $this->board_m->get_view($this->uri->segment(3), $this->uri->segment(5));
        //segment(3)은 테이블명, segment(4)는 board_id의 값 list_v.php subject부분 링크 기준 segment(5)는 board_id값임
        // $data[]는model에서 가져온 data 배열
        
        //view호출
        $this->load->view('board/view_v', $data);
        //model에서 가져온 $data[](배열)를 view_v.php 로 뿌려줌
        
        }
        
      function write(){
        echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
        
        if($_POST){
          //write_v.php의 form에서 post값을 받아오면
          
          $this->load->helper('alert'); //alert.php에서 정의 한것을 로드
          
          //주소중에서 page 세그먼트가 있는지 검사하기 위해 주로를 배열로 변환
          $uri_array = $this->segment_explode($this->uri->uri_string()); //uri_string값확인
          
            if(in_array('page', $uri_array)){
                $pages = urldecode($this->url_explode($uri_array, 'page'));
            }else{
                $pages = 1;
            }
            
            if(!$this->input->post('subject', TRUE) AND !$this->input->post('contents', TRUE)){
              //글 내용이 없을 경우, 프로그램 단에서 한번 더 체크
              alert('비정상적인 접근입니다.', '/bbs/board/lists/' .$this->uri->segment(3).'/page/' .$pages);
              exit;
              }
            // var_dump($_POST);
            $write_data = array(
              'subject' => $this->input->post('subject', TRUE),
              'contents' => $this->input->post('contents', TRUE),
              'table' => $this->uri->segment(3)
            );
            
            $result = $this->board_m->insert_board($write_data);
            
            if($result){
              alert("입력되었습니다.", '/bbs/board/lists/'.$this->uri->segment(3).'/page/'.$pages);
              exit;
              }else{
              alert("다시입력해주세요.", '/bbs/board/lists/'.$this->uri->segment(3).'/page/'.$pages);  
              exit;
              }
          }else{
            $this->load->view('board/write_v');  
          }
        }
        
        
      /**
     * url 중 키 값을 구분하여 값을 가져오도록
     *
     * @param Array $url : segment_explode 한 url 값
     * @param String $key :  가져오려는 값의 key
     * @return String $url[$k] : 리턴 값
     */
 
    function url_explode($url, $key) {
        $cnt = count($url);
 
        for ($i = 0; $cnt > $i; $i++) {
            if ($url[$i] == $key) {
                $k = $i + 1;
                return $url[$k];
            }
        }
    }
 
    /**
     * HTTP의 URL을 "/"를 Delimiter로 사용하여 배열로 바꿔 리턴한다.
     *
     * @param String 대상이 되는 문자열
     * @return string[]
     */
    function segment_explode($seg) {
        // 세그먼트 앞 뒤 "/" 제거 후 uri를 배열로 반환
 
        $len = strlen($seg);
 
        if (substr($seg, 0, 1) == '/') {
            $seg = substr($seg, 1, $len);
        }
 
        $len = strlen($seg);
 
        if (substr($seg, -1) == '/') {
            $seg = substr($seg, 0, $len - 1);
        }
 
        $seg_exp = explode("/", $seg);
        return $seg_exp;
    }

  }

 

모델 board_m.php 는

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Board_m extends CI_Model {
  
  function __construct(){
    parent::__construct();
    }
  function get_list($table = 'ci_board', $type = '', $offset = '', $limit = '', $search_word = ''){  //$type이 count이다, $offset = $start이다
    
    $sword = '';
    
    if($search_word != ''){
      //검색어 있을 경우
      $sword = ' WHERE subject like "%'.$search_word.'%" or contents like "%'.$search_word.'%" ';
      }
    
    $limit_query = '';
    
    if($limit != '' OR $offset != ''){  //$limit, $offset값이 있으면(비어있지않으면)
        //페이징이 있을 겨우처리
        $limit_query = ' LIMIT ' .$offset. ', ' .$limit;
      }
    
    $sql = "SELECT * FROM ".$table.$sword." ORDER BY board_id DESC " .$limit_query;
    
    $query = $this->db->query($sql);
    
    //count를 통해 total_row값 반환
    if($type == 'count'){
        $result = $query->num_rows();
      }else{
        $result = $query->result();
      }
    
    // $result = $query->result();
    // $result = $query->result_array();
    
    return $result;
    
    }
    /**
    
    @param string $table 게이판 테이블
    @param string $id 게시물 번호
    @return array
    
    **/
  function get_view($table, $id){
    //조회수 증가
    $sql0 = "UPDATE " .$table. " SET hits = hits + 1 WHERE board_id = '" .$id. "' ";
    $this->db->query($sql0);
    
    $sql = "SELECT * FROM " .$table. " where board_id = '".$id."'";
    $query = $this->db->query($sql);
    
    //게시물 내용 반환
    $result = $query->row();
    
    return $result;
    
    }
  function insert_board($arrays){
    $insert_array = array(
      'board_pid' => 0,
      'user_id' => 'advisor',
      'user_id' => 'palpit',
      'subject' => $arrays['subject'],
      'contents' => $arrays['contents'],
      'reg_date' => date("Y-m-d H:i:s")
    );
    
    $result = $this->db->insert($arrays['table'], $insert_array);
    
    return $result;
    }
  }

 

view_v.php

<article id="board_area">
  <header>
    <h1></h1>
  </header>
    <table cellspacing="0" cellpadding="0" class="table table-striped">
      <thead>
      <tr>
        <th scope="col"><?php echo $views-> subject; ?></th>
        <th scope="col">이름 : <?php echo $views-> user_name; ?></th>
        <th scope="col">조회수 : <?php echo $views-> hits; ?></th>
        <th scope="col">등록일 : <?php echo $views-> reg_date; ?></th>
      </tr>
      </thead>
      <tbody>
        <tr>
          <th colspan="4">
            <?php echo $views-> contents; ?>
          </th>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th colspan="4">
            <a href="/bbs/board/lists/<?php echo $this->uri->segment(3); ?>/page/<?php echo $this->uri->segment(7); ?>" class="btn btn-primary">목록</a><?php echo $this->uri->segment(7); ?>
            /<?php echo $page;?>
            <a href="/bbs/board/modify/<?php echo $this->uri->segment(3); ?>/board_id/
            <?php echo $this->uri->segment(4); ?>/page/<?php echo $this->uri->segment(7); ?>"
             class="btn btn-warning">수정</a>
            <a href="/bbs/board/delete/<?php echo $this->uri->segment(3); ?>/board_id/
            <?php echo $this->uri->segment(5); ?>/page/<?php echo $this->uri->segment(7); ?>"
             class="btn btn-danger">삭제</a>
            <a href="/bbs/board/write/<?php echo $this->uri->segment(3); ?>/page/
            <?php echo $this->uri->segment(7); ?>" class="btn btn-success">쓰기</a>
          </th>
        </tr>
      </tfoot>
    </table>
</article>

일단 다올려 봅니다. 말씀하신게 lists_v.php말씀하신게 맞죠 첨에 view_v.php를 올렸네요!

변종원(웅파) / 2017/01/13 16:05:03 / 추천 0

세그먼트 7이 적용됐다는 것은 검색어가 있다는 것인데 나온 쿼리는 검색어가 없을때의 쿼리 입니다.

결론적으로 검색어가 없다면 세그먼트 5에서 페이지를 가지고 와서 $start 값을 계산합니다.

그 값이 쿼리에서 limit 0, 10 형태로 사용되는 것인데 -5라는 값이 들어가서 문제가 됩니다.

리스트 메소드에서 세그먼트5, 7, $data['page'] 변수들을 출력해보세요.

유후~ / 2017/01/17 12:29:25 / 추천 0

드디어 문제 해결 했네요 이것때문에 이것 저것 만져 보다 드디어 해결 했습니다.

혹시 몰라 올립니다. 

list_v.php 에서 subject 부분 링크시 줄바꿈하면 엔터 값이 들어 간것 같습니다.

그래서 줄바꾸지 않고 일렬로 써보니 %20%20..... 값이 딸려 드러가지 않습니다. 에휴 ㅠㅠ 

어쨌든 이것 때문에 여러번 다시 만들고 만들고 하면서 이해도는 많이 높아졌습니다. ㅋㅋ