如何使用 PHP 和 PDO 在一個回應中傳回多個回應資料?
Oct 27, 2024 am 06:02 AM在一個回應中傳回多個回應資料
提供的程式碼嘗試從資料庫中擷取多筆記錄並在單一回應中傳回它們。但是,由於 fetchAll 的錯誤使用,無法合併結果並傳回所需的輸出。
以下程式碼提供了更正的解決方案:
<code class="php">try { $dbAdapter = new DbAdapter(); $connection = $dbAdapter->connect(); // User IDs to be fetched. $userIds = [1, 2]; // The sql statement - it will be prepared. $sql = 'SELECT users.id AS userid, users.name AS username, subjects.id AS subject_id, subjects.name AS subject_name, subjects.points AS active_points, IFNULL(SUM(subjects.points), 0) AS total_points, ( SELECT IFNULL(SUM(points), 0) FROM subjects WHERE userid = users.id AND semester = 1 ) AS semester_1_points, ( SELECT IFNULL(SUM(points), 0) FROM subjects WHERE userid = users.id AND semester = 2 ) AS semester_2_points, ( SELECT IFNULL(SUM(points), 0) FROM subjects WHERE userid = users.id AND semester = 3 ) AS semester_3_points FROM tbsubjects AS subjects LEFT JOIN tbusers AS users ON users.id = subjects.userid WHERE subjects.userid IN (:userIds) GROUP BY subjects.userid ORDER BY subjects.time DESC'; // The input parameters list for the prepared sql statement. $bindings = array( ':userIds' => $userIds, ); // Prepare and validate the sql statement. $statement = $connection->prepare($sql); if (!$statement) { throw new UnexpectedValueException('The sql statement could not be prepared!'); } // Bind the input parameters to the prepared statement. foreach ($bindings as $key => $value) { $bound = $statement->bindValue( getInputParameterName($key), $value, getInputParameterDataType($value) ); if (!$bound) { throw new UnexpectedValueException('An input parameter can not be bound!'); } } // Execute the prepared statement. $executed = $statement->execute(); if (!$executed) { throw new UnexpectedValueException('The prepared statement could not be executed!'); } // Fetch users list - array of objects. $users = $statement->fetchAll(PDO::FETCH_OBJ); if ($users === FALSE) { throw new UnexpectedValueException('Fetching users list failed!'); } // Close connection. $connection = NULL; // Handle results. if (empty($users)) { $response->getBody()->write( '{ "error": { "message":"Invalid" } }' ); } else { $response->getBody()->write(json_encode($users)); } } catch (PDOException $exc) { echo $exc->getMessage(); // $logger->log($exc); exit(); } catch (Exception $exc) { echo $exc->getMessage(); // $logger->log($exc); exit(); }</code>
登入後複製
在此解決方案中:
- fetchAll 方法與PDO::FETCH_OBJ 一起使用來檢索物件數組,其中每個物件代表結果集中的一行。
- 自訂 getInputParameterName() 和 getInputParameterDataType () 函數用於將輸入參數正確綁定到準備好的語句。
- IFNULL 函數用於處理total_points、sememer_1_points、sememer_2_points 和ememer_3_points 列中的空值,確保它們在以下情況下返回為零: null。
因此,此程式碼正確地從資料庫中取得多行並將它們合併為單一回應,該回應與預期輸出相符。
以上是如何使用 PHP 和 PDO 在一個回應中傳回多個回應資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在 Linux 中運行 MySQl(有/沒有帶有 phpmyadmin 的 podman 容器)
