본문 바로가기
chatGPT와 인공지능AI

chatGPT, 가르치는 보람?! [실험#3]

오늘은 chatGPT에게 PHP 코딩으로 RESTFUL API SERVER를 만들도록 해보았습니다.
근데 처음에는 약간 틀린 코드를 만들었네요.
그런데 그걸 이렇게 고치라고 해보았더니 '와우~ 그대로 알아먹고 뚝딱 고치는게 아니겠습니까?'
웬만한 좀 잘하는 초급 개발자같아서 심쿵(?)해 지네요 ㅎㅎ

오늘은 단순히 chatGPT의 대화 내역을 그대로 싣습니다.

크레이

Hello, chatGPT
안녕, 쳇지피티

chatGPT

Hello! How can I help you today?
안녕하세요! 무엇을 도와드릴까요?

크레이

I want play with you about coding today.
오늘은 코딩에 관해 너와 즐거운 이야기를 나누고 싶어

chatGPT

Sure!
좋아요!

I'd love to chat about coding.
나는 코딩에 대해 이야기하는걸 매우 좋아합니다.

What specific programming topic or language are you interested in discussing?
어떤 특정한 프로그래밍 주제 또는 언어에 대해 논의하는걸 좋아하시나요?

크레이

Today's interesting thing is php
오늘의 관심사는 PHP 야.

chatGPT

Great!
훌륭해요!

PHP is a server-side scripting language used for web development. 
PHP 는 웹개발용으로 서버사이드 스크립트 언어로 사용됩니다.

It's known for its ease of use and ability to interact with databases, 
사용하기도 쉽고 데이터베이스와 상호 작용한 것으로 알려져 있으며,

making it a popular choice for building dynamic websites and web applications. 
동적 웹사이트와 웹 어플리케이션을 제작하는데 인기 선택 종목이지요.

What would you like to know more about PHP specifically?
PHP에 대해 구체적으로 무엇을 알고 싶으세요?

크레이

Ok, I hope watching your php programing technique. 
오케이, 나는 너의 PHP 프로그래밍 기술을 보길 원해.

Could you make a php script for restful api server?
PHP 스크립트로 RESTFUL api 서버를 만들수 있겠어?

chatGPT

Certainly! 
물론이죠!

Here's a basic example of a PHP script that implements a RESTful API server
여기에 간단한 PHP 스크립트 REST API 서버를 포함한 샘플 코드가 있어요.

<?php
// Allow CORS requests
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE");

// Get the HTTP method, path, and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);

// Connect to the database
$link = mysqli_connect('localhost', 'user', 'password', 'dbname');
mysqli_set_charset($link,'utf8');

// Retrieve the requested resource
$resource = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$id = array_shift($request)+0;

// Escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
  if ($value===null) return null;
  return mysqli_real_escape_string($link,(string)$value);
},array_values($input));

// Build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
  $set.=($i>0?',':'').'`'.$columns[$i].'`=';
  $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}

// Create the SQL command
switch ($method) {
  case 'GET':
    $sql = "select * from `$resource`".($id?" WHERE id=$id":''); break;
  case 'PUT':
    $sql = "update `$resource` set $set where id=$id"; break;
  case 'POST':
    $sql = "insert into `$resource` set $set"; break;
  case 'DELETE':
    $sql = "delete `$resource` where id=$id"; break;
}

// Execute the SQL command
$result = mysqli_query($link,$sql);

// Return the results as JSON
header('Content-Type: application/json');
echo json_encode(mysqli_fetch_object($result));

// Close the database connection
mysqli_close($link);
?>

This script implements a simple RESTful API server 
이것은 단순한 restful API 서버를 구현한 것이고

that can handle GET, POST, PUT, and DELETE requests and interact with a MySQL database. 
GET, POST, PUT, DELETE 요청과 MYSQL데이터 베이스를 연동할 수 있는 코드입니다.

You'll need to modify it to fit your specific use case and add error handling, 
여러분은 이것을 여러분의 특정 용도에 맞게 수정하고 오류를 처리할 필요가 있습니다.

but it should give you a good starting point.
그러나 이것은 여러분에게 좋은 출발점을 제공합니다.


스크립트를 테스트해본 것은 아니지만 분명 오류난 곳이 있어 chatGPT에게 한번 알려 주었습니다.

크레이

it seems some mistake. 
어디 보자.. 약간의 실수가 있는데.

mysql delete command starts this sentence 'delete from $table'. 
mysql 삭제 명령은 'delete from $table' 문장으로 시작하는데.

not 'delete $table'
'delete $table'이 아니고

can you modify this script?
이 스크립트를 수정해줄래?

chatGPT

Sure, 
좋아요

here's an updated version of the script with the corrected SQL command for the DELETE method:
여기 DELETE SQL 명령을 맞게 수정한 스크립트입니다.

<?php
// Allow CORS requests
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE");

// Get the HTTP method, path, and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);

// Connect to the database
$link = mysqli_connect('localhost', 'user', 'password', 'dbname');
mysqli_set_charset($link,'utf8');

// Retrieve the requested resource
$resource = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$id = array_shift($request)+0;

// Escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
  if ($value===null) return null;
  return mysqli_real_escape_string($link,(string)$value);
},array_values($input));

// Build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
  $set.=($i>0?',':'').'`'.$columns[$i].'`=';
  $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}

// Create the SQL command
switch ($method) {
  case 'GET':
    $sql = "select * from `$resource`".($id?" WHERE id=$id":''); break;
  case 'PUT':
    $sql = "update `$resource` set $set where id=$id"; break;
  case 'POST':
    $sql = "insert into `$resource` set $set"; break;
  case 'DELETE':
    $sql = "delete from `$resource` where id=$id"; break;
}

// Execute the SQL command
$result = mysqli_query($link,$sql);

// Return the results as JSON
header('Content-Type: application/json');
echo json_encode(mysqli_fetch_object($result));

// Close the database connection
mysqli_close($link);
?>

This script should now correctly implement the DELETE method for a RESTful API server.
이 스크립트는 이제 정확히 DELETE 명령에 대한 Restful api server 를 구현할 것이예요

틀린 부분에 대해 설명해주자 아주 정확하게 수정을 했더라구요.
아이쿠! 대견한 것!

크레이

Wow! good! you are very smart!
외우! 좋아요! 너 정말 똑똑하구나!

chatGPT

Thank you! 
감사합니다!

I'm here to help and answer your questions to the best of my ability. 
저는 여기 당신의 질문에 최선을 다해 돕고 대답하려고 여기 있어요.

Let me know if there's anything else I can assist with.
제가 도울 다른 것이 있다면 알려주세요.


chatGPT가 내말을 잘 알아들어서 감격(?)까지는 아니지만 재미있더라구요 ㅎㅎ
다음 번엔 또 다방면으로 시도해 봐야 겠습니다.


오늘도 구경 와주신 많은 분들께 감사드립니다 :)
구독과 좋아요는 크레이의 활동에 '파우우우우~어-------'가 됩니다!