prepare('SELECT id FROM chains WHERE from_word = ?'); $stmt->execute([$start_word]); $row = $stmt->fetch(PDO::FETCH_ASSOC); if (!$row) { $start_word = null; array_splice($question_parts, $word_index, 1); } } // selecting a random word from db if there is no question if (!$question) { $stmt = $db->query('SELECT from_word FROM chains ORDER BY rand() LIMIT 1'); $stmt->execute(); if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $start_word = $row['from_word']; } } if (!$start_word && !$question) { http_response_code(400); header('Content-Type: application/json'); echo json_encode([ 'status_code' => 400, 'message' => 'No question.', 'data' => null ], JSON_UNESCAPED_SLASHES); exit; } // generating markov chain $output = []; while (strlen(implode(' ', $output)) < $max_length) { array_push($output, $start_word); $stmt = $db->prepare('SELECT to_word FROM chains WHERE from_word = ? ORDER BY rand() LIMIT 1'); $stmt->execute([$start_word]); $row = $stmt->fetch(PDO::FETCH_ASSOC); if (!$row) { break; } $start_word = $row['to_word']; } header('Content-Type: application/json'); echo json_encode([ 'status_code' => 200, 'message' => null, 'data' => [ 'answer' => implode(' ', $output) ?: '...' ] ], JSON_UNESCAPED_SLASHES); ?>