How to Utilize MySQLi from a Separate Class in PHP
Introduction
Upgrading from PHP 5.6 to 7.0 necessitates switching from MySQL to MySQLi, which may disrupt existing setups. This article addresses an issue encounter when attempting to access a MySQLi connection from a separate class.
Problem
A programmer attempted to access a MySQLi connection created in a database class from an API class, encountering an internal server error (500) when calling the connection. However, connecting directly within the API class resolved the issue.
Solution
Several recommended changes can rectify the problem:
Example Code:
database.php:
<code class="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">class MyAPI { protected $db; public function __construct($db, $request_uri, $postData, $origin) { $this->db = $db; } }</code>
app.php:
<code class="php">require 'database.php'; require 'myapi.php'; $api = new MyAPI($db, $request_uri, $postData, $origin);</code>
The above is the detailed content of Here are a few title options, keeping in mind the question format and focus on the MySQLi issue: **Direct and Concise:** * **Why Can\'t I Access My MySQLi Connection from a Separate Class?** * **MyS. For more information, please follow other related articles on the PHP Chinese website!