Using MySQLi from Another Class in PHP: A Detailed Breakdown
In this query, the user has upgraded MySQL to MySQLi after transitioning from PHP 5.6 to 7.0. After following the guide "Using MySQLi in other classes," they encountered internal server error 500 when attempting to access a database connection from a different class.
To understand the error, let's examine the user's PHP code. They have three classes: a Database class for establishing the MySQLi connection, a MyAPI class where they try to access this connection, and a separate function where they make the actual database query.
Error Analysis
The problem arises from several fundamental issues in the code:
Solution
To address these issues, the following steps are recommended:
Here's an improved PHP code example:
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_once 'Database.php'; # require_once 'myapi.php'; require 'vendor/autoload.php'; // autoloading is a must $api = new MyAPI($db, $request_uri, $postData, $origin); $user = $api->getUser($_POST['id']);
With these modifications, the user should be able to establish a proper MySQLi connection and perform database queries from different classes.
The above is the detailed content of How to Properly Access a MySQLi Database Connection from Different Classes in PHP?. For more information, please follow other related articles on the PHP Chinese website!