在類別中使用 MySQLi:故障排除指南
在不同類別中使用 MySQLi 可能具有挑戰性,但不用擔心。讓我們深入探討您遇到的問題並提供解決方案。
問題:內部伺服器錯誤500
解決方案: 在 MyAPI 建構子中初始化資料庫物件並將其作為需要資料庫連接的其他函數的參數。這可確保共用連線的所有類別都直接引用相同實例。
範例:
<code class="php">// myapi.php class MyAPI { private $db; public function __construct($db) { $this->db = $db; } public function getUser($id) { $result = mysqli_query($this->db->conn, "SELECT * FROM users WHERE id='$id'"); return mysqli_fetch_assoc($result); } } // app.php // Initialize database once $db = new mysqli(...); // Create MyAPI instance with database reference $api = new MyAPI($db); // Use MyAPI to access user information $user = $api->getUser(1);</code>
其他注意事項:
按照以下步驟,您應該可以成功使用來自不同類別的 MySQLi PHP。
以上是如何在 PHP 中的不同類別之間共用 MySQLi 連線?的詳細內容。更多資訊請關注PHP中文網其他相關文章!