Home >Database >Mysql Tutorial >How to Properly Use MySQLi Connections Across Different PHP Classes?
When upgrading from PHP 5.6 to 7.0, it is necessary to update from MySQL to MySQLi. However, this can sometimes lead to setup issues.
Problem:
After upgrading to PHP 7.0 and MySQLi, attempting to access database connections using $this->db->conn results in an internal server error 500, even though creating the database connection directly in the class works.
Solution:
The error is caused by several bad practices:
To resolve the issue:
Example Code:
// database.php $db = new mysqli("localhost", "DBUserName", "UserPassword", "SelectedDB"); $db->set_charset('utf8mb4');
// myapi.php class MyAPI { protected $db; public function __construct($db, $request_uri, $postData, $origin) { $this->db = $db; } // ... (rest of the class omitted for brevity) }
// app.php require 'vendor/autoload.php'; // assuming autoloading is set up $api = new MyAPI($db, $request_uri, $postData, $origin); $user = $api->getUser($_POST['id']);
By following these guidelines, you can successfully use MySQLi from other classes in PHP.
The above is the detailed content of How to Properly Use MySQLi Connections Across Different PHP Classes?. For more information, please follow other related articles on the PHP Chinese website!