드롭다운으로 한국산업분류 적용하기. > 그누보드5 팁자료실

그누보드5 팁자료실

드롭다운으로 한국산업분류 적용하기. 정보

드롭다운으로 한국산업분류 적용하기.

첨부파일

k_industry.zip (34.2K) 6회 다운로드 2025-04-10 04:12:47

본문

2106540763_1744225936.5784.png

한국산업분류를 드롭다운식으로 선택할수있게 만들어보았습니다.

대분류, 중분류, 소분류, 세분류, 세세분류 이렇게 5단계로 되어있는데요.

대분류, 중분류, 소분류, 세분류 까지만 선택할수있게 해보았습니다.

첨부한 insert_industry.sql 을 보면 나오는 

CREATE TABLE k_industry (
    id INT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    parent_id INT DEFAULT NULL,
    depth INT NOT NULL
);

으로 테이블을 만들고  아래의 데이타를 입력해줍니다.
INSERT INTO k_industry (id, name, parent_id, depth) VALUES (1, '농업, 임업 및 어업 (01 ~ 03)', NULL, 1);
INSERT INTO k_industry (id, name, parent_id, depth) VALUES (100, '농업', 1, 2);
INSERT INTO k_industry (id, name, parent_id, depth) VALUES (1000, '작물 재배업', 100, 3);
....

첨부된 industry_select.php에서 데이타베이스를 연결하고 업로드하면 드롭다운식으로 분류가 나옵니다.

챗gpt에 물어서 만든것이기 때문에 저한테 물어도 잘 모릅니다.^^

inustry_select.php


<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// 데이타베이스 연결 
include_once("../db/connect.php");
// AJAX 요청 처리
if (isset($_GET['depth'])) {
    header('Content-Type: application/json');
    $depth = intval($_GET['depth']);
    // 빈 문자열이면 NULL로 처리
    $parent_id = (isset($_GET['parent_id']) && $_GET['parent_id'] !== '') ? intval($_GET['parent_id']) : null;
    $sql = "SELECT id, name FROM k_industry WHERE depth = ?";
    $params = [$depth];
    if ($parent_id !== null) {
        $sql .= " AND parent_id = ?";
        $params[] = $parent_id;
    } else {
        $sql .= " AND parent_id IS NULL";
    }
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    exit;
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>산업 분류 선택</title>
</head>
<body>
  <h2>산업분류 선택</h2>
  <form method="post" action="submit.php"> <!-- 추후 데이터 저장 -->
    <label>대분류:
      <select id="depth1" name="depth1">
        <option value="">선택</option>
      </select>
    </label>
    <br><br>
    <label>중분류:
      <select id="depth2" name="depth2">
        <option value="">선택</option>
      </select>
    </label>
    <br><br>
    <label>소분류:
      <select id="depth3" name="depth3">
        <option value="">선택</option>
      </select>
    </label>
    <br><br>
    <label>세분류:
      <select id="depth4" name="depth4">
        <option value="">선택</option>
      </select>
    </label>
    <br><br>
    <button type="submit">제출</button>
  </form>
  <script>
    // 공통 함수: 분류 불러오기
    function fetchCategories(depth, parentId, targetId) {
      const target = document.getElementById(targetId);
      target.innerHTML = '<option value="">선택</option>';
      let url = `industry_select.php?depth=${depth}`;
      if (parentId !== null && parentId !== '') {
        url += `&parent_id=${parentId}`;
      }
      fetch(url)
        .then(res => res.json())
        .then(data => {
          data.forEach(row => {
            const option = document.createElement('option');
            option.value = row.id;
            option.textContent = row.name;
            target.appendChild(option);
          });
        })
        .catch(error => console.error('Error fetching data:', error));
    }
    // 대분류 로딩: parentId를 null로 전달
    window.onload = function () {
      fetchCategories(1, null, 'depth1');
    };
    // 중분류: 대분류 선택 시
    document.getElementById('depth1').addEventListener('change', function () {
      const parentId = this.value;
      fetchCategories(2, parentId, 'depth2');
      document.getElementById('depth3').innerHTML = '<option value="">선택</option>';
      document.getElementById('depth4').innerHTML = '<option value="">선택</option>';
    });
    // 소분류: 중분류 선택 시
    document.getElementById('depth2').addEventListener('change', function () {
      const parentId = this.value;
      fetchCategories(3, parentId, 'depth3');
      document.getElementById('depth4').innerHTML = '<option value="">선택</option>';
    });
    // 세분류: 소분류 선택 시
    document.getElementById('depth3').addEventListener('change', function () {
      const parentId = this.value;
      fetchCategories(4, parentId, 'depth4');
    });
  </script>
</body>
</html>

 

추천
7

댓글 6개

전체 2,638 |RSS
그누보드5 팁자료실 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT