테스트 사이트 - 개발 중인 베타 버전입니다

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

· 6개월 전 · 701 · 6

2106540763_1744225936.5784.png

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

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

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

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

[code]CREATE TABLE k_industry (
    id INT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    parent_id INT DEFAULT NULL,
    depth INT NOT NULL
);[/code]
으로 테이블을 만들고  아래의 데이타를 입력해줍니다.

[code]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);
....[/code]

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

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

inustry_select.php

[code]

<?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>

[/code]

 

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

댓글 6개

6개월 전

감사합니다 ^^

6개월 전

@민트다이어리 

감사합니다 ^^

감사합니다.

6개월 전

@써맨 

감사합니다 ^^

6개월 전

감사 합니다.

6개월 전

감사합니다.

게시글 목록

번호 제목
23966
23963
23953
23949
23938
23935
23933
23928
23919
23918
23917
23910
23902
23901
23897
23894
23893
23891
23885
23872
23870
23862
23859
23853
23845
23838
23827
23819
23805
23801