要將資料合併到單一回應並傳回預期輸出,請使用下列方法:
<code class="sql">SELECT subjects.userid, users.name AS username, ( SELECT id FROM tbsubjects WHERE userid = subjects.userid ORDER BY id ASC LIMIT 1 ) AS subjectsid, ( SELECT name FROM tbsubjects WHERE userid = subjects.userid ORDER BY time DESC LIMIT 1 ) AS subjectname, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND month = DATE_FORMAT(NOW(), "%c") ) AS activepts, IFNULL(SUM(subjects.points), 0) AS totalpts, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 1 ) AS sem1, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 2 ) AS sem2, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 3 ) AS sem3 FROM tbsubjects AS subjects LEFT JOIN tbusers AS users ON users.id = subjects.userid WHERE subjects.userid = :userid1 GROUP BY subjects.userid ORDER BY subjects.time DESC;</code>
如果使用者清單為空,則傳回 JSON 格式的錯誤訊息:
<code class="php">$response->getBody()->write( '{ "error": { "message":"Invalid" } }' );</code>
否則,傳回 JSON 編碼的使用者清單。
假設您的主題表與初始描述中的結構相同,您可以使用以下腳本獲取並格式化所需的資料:
<code class="php"><?php $userid1 = 1; // Replace this with the actual user ID // SQL statement $sql = 'SELECT ... FROM ... WHERE subjects.userid = :userid1 GROUP BY ... ORDER BY ...'; // Bindings $bindings = array( ':userid1' => $userid1 ); // Fetch users $users = $dbAdapter->fetchAll($sql, $bindings); // Handle results if (empty($users)) { // Handle empty users list } else { // Handle users list }</code>
該腳本假設您有一個提供資料庫互動方法的DbAdapter 類別。這個類別應該處理連接建立、語句準備和資料檢索。
以上是如何在 PHP 中的一個回應中傳回多個回應資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!