API 구현 기초

아기코딩단2·2023년 11월 29일

목적 정의: 데이터 검색

개발 환경 설정: PHP, PDO사용

데이터베이스 설계: 기존 구조 사용 / image_path 컬럼 추가

API 엔드포인트 개발: ~api/?idx=1

select.php

<?php
require_once __DIR__.'/config.php';

class API {
    function Select() {
        $db = new Connect;
        $chonnam = array();

        // idx 파라미터 받기
        $idx = isset($_GET['idx']) ? $_GET['idx'] : null;

        if ($idx) {
            // 특정 idx에 대한 데이터만 조회
            $data = $db->prepare('SELECT * FROM chonnam WHERE idx = :idx');
            $data->bindValue(':idx', $idx, PDO::PARAM_INT);
        } else {
            // 모든 데이터 조회
            $data = $db->prepare('SELECT * FROM test ORDER BY idx');
        }

        $data->execute();

        while($OutputData = $data->fetch(PDO::FETCH_ASSOC)) {
            $test[$OutputData['idx']] = array(
                'idx' => $OutputData['idx'],
                'name' => $OutputData['name'],
                'image_path' => $OutputData['image_path']
            );
        }
        return json_encode($test, JSON_UNESCAPED_UNICODE);
    }
}
// header('Content-Type: application/json'); //html 반환할 때는 적합하지 않음
$API = new API; // API 객체 생성
echo $API->Select(); // Select 메소드 호출

?>

index.php


<?php
require_once __DIR__.'/select.php';

$API = new API;
$jsonData = $API->Select();
$datas = json_decode($jsonData, true); // JSON을 PHP 배열로 변환
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <?php foreach($datas as $data): ?>
        <div>
            <img src="<?php echo htmlspecialchars($data['image_path'], ENT_QUOTES, 'UTF-8') ?>" alt="<?php echo htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8') ?>">
        </div>
    <?php endforeach; ?>
</body>
</html>

발생 문제점 : html 의 코드가 그대로 출력되는 현상 발생
// header('Content-Type: application/json'); //html 반환할 때는 적합하지 않음
select.php 에서 주석 처리함으로서 완료

profile
레거시 학살자

0개의 댓글