Home > Article > Backend Development > How to Share a MySQLi Connection Between Different Classes in PHP?
Using MySQLi in Classes: A Troubleshooting Guide
Using MySQLi from different classes can be challenging, but don't worry. Let's dive into the issues you've encountered and provide a solution.
Problem: Internal Server Error 500
Solution: Initialize the Database object within the MyAPI constructor and pass it as a parameter to other functions requiring a database connection. This ensures that all classes sharing the connection have a direct reference to the same instance.
Example:
<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>
Additional Considerations:
By following these steps, you should be able to successfully use MySQLi from different classes in PHP.
The above is the detailed content of How to Share a MySQLi Connection Between Different Classes in PHP?. For more information, please follow other related articles on the PHP Chinese website!