/
home
/
efamember
/
domains
/
efa-member.com
/
public_html
/
chat
/
up file
home
<?php header("Content-Type: application/json"); // ตั้งค่าการเชื่อมต่อฐานข้อมูล $host = "localhost"; $username = "fordev_newtem"; // เปลี่ยนตามของคุณ $password = "0LqUtB51D"; // เปลี่ยนตามของคุณ $database = "fordev_newtem"; // เปลี่ยนตามของคุณ $conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die(json_encode(["reply" => "ไม่สามารถเชื่อมต่อกับฐานข้อมูล"])); } // ใส่ OpenAI API Key ของคุณ $api_key = "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"; // รับข้อความจาก JavaScript $data = json_decode(file_get_contents("php://input"), true); $user_message = $data["message"]; // ดึงรายชื่อตารางทั้งหมด $tables_query = $conn->query("SHOW TABLES"); $tables = []; while ($row = $tables_query->fetch_array()) { $tables[] = $row[0]; } // ดึงโครงสร้างคอลัมน์ของแต่ละตาราง $schema_info = []; foreach ($tables as $table) { $columns_query = $conn->query("SHOW COLUMNS FROM $table"); $columns = []; while ($col = $columns_query->fetch_assoc()) { $columns[] = $col['Field']; } $schema_info[$table] = $columns; } // ตรวจสอบว่าผู้ใช้ถามเกี่ยวกับข้อมูลอะไร $sql = ""; $db_result = ""; $selected_table = ""; foreach ($tables as $table) { if (stripos($user_message, $table) !== false) { $selected_table = $table; break; } } if ($selected_table !== "") { $sql = "SELECT * FROM $selected_table LIMIT 5"; // จำกัดผลลัพธ์แค่ 5 แถว $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $db_result .= json_encode($row, JSON_UNESCAPED_UNICODE) . "\n"; } } else { $db_result = "ไม่มีข้อมูลในตารางนี้"; } } // สร้างข้อมูลที่จะส่งไปให้ OpenAI $context = "ฐานข้อมูลนี้มีตารางดังนี้: " . implode(", ", array_keys($schema_info)) . "\n"; foreach ($schema_info as $table => $columns) { $context .= "ตาราง $table มีคอลัมน์: " . implode(", ", $columns) . "\n"; } $context .= "ผู้ใช้ถาม: " . $user_message . "\n"; $context .= "ข้อมูลที่เกี่ยวข้อง: " . $db_result; // ส่งข้อความไปที่ OpenAI API $ch = curl_init("https://api.openai.com/v1/chat/completions"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Authorization: Bearer $api_key", "Content-Type: application/json" ]); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ "model" => "gpt-4o-mini", "messages" => [ ["role" => "system", "content" => "You are a chatbot that can answer questions about the database structure and its data."], ["role" => "user", "content" => $context] ] ])); $response = curl_exec($ch); curl_close($ch); $conn->close(); // แปลงผลลัพธ์และส่งกลับ $response_data = json_decode($response, true); $reply = $response_data["choices"][0]["message"]["content"] ?? "เกิดข้อผิดพลาด"; echo json_encode(["reply" => $reply]); ?>