Accessing MySQLi from an External Class in PHP
Problem:
After upgrading from PHP 5.6 to 7.0, an existing setup that utilizes both MySQL and MyAPI classes has encountered issues. Specifically, accessing the database connection from the MyAPI class results in a 500 internal server error.
Solution:
There are several practices that contribute to this error:
Code Structure:
Create three files:
database.php:
<code class="php"><?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $db = new mysqli("localhost", "DBUserName", "UserPassword", "SelectedDB"); $db->set_charset('utf8mb4');</code>
myapi.php:
<code class="php"><?php class MyAPI { protected $db; public function __construct($db) { $this->db = $db; } public function getUser($id) { // Define SQL query and subsequent operations to fetch user data. } }</code>
app.php:
<code class="php"><?php require 'database.php'; require 'myapi.php'; $api = new MyAPI($db); $user = $api->getUser($_POST['id']);</code>
By following these guidelines and separating database concerns from class functionality, the issue of accessing MySQLi from an external class can be effectively resolved.
The above is the detailed content of How to Access MySQLi from an External Class in PHP 7.0?. For more information, please follow other related articles on the PHP Chinese website!