Home >Database >Mysql Tutorial >How Can I Properly Access a MySQLi Database Connection from Different PHP Classes?
When upgrading from PHP 5.6 to 7.0, it is essential to transition from MySQL to MySQLi. This transition can introduce challenges, particularly when attempting to access MySQLi connections from separate classes. This question highlights one such situation where an attempt to connect to a database from an API class using a database class led to an internal server error.
The root of the issue lies in adhering to good programming practices. Extending a user from a database class is incorrect, and the database class itself lacks significant functionality. To resolve this error and improve the overall design, consider the following steps:
database.php <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $db = new mysqli("localhost", "DBUserName", "UserPassword", "SelectedDB"); $db->set_charset('utf8mb4');
myapi.php <?php class MyAPI { protected $db; public function __construct($db, $request_uri, $postData, $origin) { $this->db = $db; } public function getUser($id) { $sql = "SELECT * FROM users where>
app.php <?php require 'vendor/autoload.php'; // autoloading is recommended $api = new MyAPI($db, $request_uri, $postData, $origin); $user = $api->getUser($_POST['id']);
The above is the detailed content of How Can I Properly Access a MySQLi Database Connection from Different PHP Classes?. For more information, please follow other related articles on the PHP Chinese website!