Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-26 08:21:30
Original
220 people have browsed it

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>
Copy after login

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>
Copy after login

app.php:

<code class="php"><?php
require 'database.php';
require 'myapi.php';

$api = new MyAPI($db);
$user = $api->getUser($_POST['id']);</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template