Home > Article > Backend Development > Why Am I Getting a \'500 Internal Server Error\' When Accessing a MySQLi Connection from a Separate Class in PHP?
How to Access MySQLi from a Separate Class in PHP
You are encountering an error when attempting to establish a database connection from a separate class in PHP using MySQLi. The error is "Internal Server Error 500" when you try to access the connection object, indicating a problem with your code or configuration.
To resolve this issue, let's analyze the code and identify key points:
Database Class:
The database class contains the necessary information for connecting to the database, such as the server name, user name, password, and database name.
API Class:
Within the API class, you initialize the $db property with new Database(). This establishes a new database connection object, which is different from the connection created within the __construct method of the database class.
Function Call:
You are then attempting to execute a query using the $this->db->conn object, which is undefined within the MyAPI class. This is because the $conn property is only defined within the Database class.
Solution:
To access the database connection object within the MyAPI class, you need to pass it as a constructor argument when creating a new instance of Database.
Here's the corrected code:
Database.php:
<code class="php">class Database { private $conn; public function __construct() { $this->conn = new mysqli(...connection details...); } public function getConn() { return $this->conn; } }</code>
MyAPI.php:
<code class="php">class MyAPI { private $db; public function __construct($db) { $this->db = $db; } public function getUser($id) { $sql = ...query...; $result = mysqli_query($this->db->getConn(), $sql); return mysqli_fetch_assoc($result); } }</code>
app.php:
<code class="php">$db = new Database(); $api = new MyAPI($db); $user = $api->getUser($_POST['id']);</code>
This approach ensures that the database connection object is accessible within the MyAPI class, allowing you to execute queries and retrieve data successfully.
The above is the detailed content of Why Am I Getting a \'500 Internal Server Error\' When Accessing a MySQLi Connection from a Separate Class in PHP?. For more information, please follow other related articles on the PHP Chinese website!