Here are a few title options, keeping in mind the question format and focus on the MySQLi issue: **Direct and Concise:** * **Why Can\'t I Access My MySQLi Connection from a Separate Class?** * **MyS

Barbara Streisand
Release: 2024-10-25 12:52:30
Original
486 people have browsed it

Here are a few title options, keeping in mind the question format and focus on the MySQLi issue:

**Direct and Concise:**

* **Why Can't I Access My MySQLi Connection from a Separate Class?**
* **MySQLi Connection Issues: Accessing from a Different Class

How to Utilize MySQLi from a Separate Class in PHP

Introduction

Upgrading from PHP 5.6 to 7.0 necessitates switching from MySQL to MySQLi, which may disrupt existing setups. This article addresses an issue encounter when attempting to access a MySQLi connection from a separate class.

Problem

A programmer attempted to access a MySQLi connection created in a database class from an API class, encountering an internal server error (500) when calling the connection. However, connecting directly within the API class resolved the issue.

Solution

Several recommended changes can rectify the problem:

  • Eliminate the Database Class: The database class is redundant as it lacks functionality.
  • Create a Single MySQLi Instance: Establish a single MySQLi instance using the native mysqli class.
  • Pass the Instance as a Parameter: Inject the MySQLi instance as a constructor parameter into classes requiring database connectivity.

Example Code:

database.php:

<code class="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">class MyAPI
{
    protected $db;

    public function __construct($db, $request_uri, $postData, $origin)
    {
        $this->db = $db;
    }
}</code>
Copy after login

app.php:

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

$api = new MyAPI($db, $request_uri, $postData, $origin);</code>
Copy after login

The above is the detailed content of Here are a few title options, keeping in mind the question format and focus on the MySQLi issue: **Direct and Concise:** * **Why Can\'t I Access My MySQLi Connection from a Separate Class?** * **MyS. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!