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:
// 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);
Additional Considerations:
By following these steps, you should be able to successfully use MySQLi from different classes in PHP.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3