Home  >  Article  >  Backend Development  >  How to Access MySQLi from an External Class in PHP 7.0?

How to Access MySQLi from an External Class in PHP 7.0?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 08:21:30155browse

How to Access MySQLi from an External Class in PHP 7.0?

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:

  1. Avoid Inheritance: Extending MyAPI from a Database class is redundant and unnecessary.
  2. Remove Redundant Database Class: The Database class serves no practical purpose since it primarily establishes a connection, which can be easily achieved via the vanilla mysqli class.
  3. Create a Centralized Database Instance: Establish a single, global instance of the database connection and pass it to each class that requires database access.

Code Structure:

Create three files:

  • database.php: Contains the database connection logic.
  • myapi.php: Defines the MyAPI class with dependency injection for the database connection.
  • app.php: Acts as the entry point and instantiates the MyAPI class, passing the database connection.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn