Home >Database >Mysql Tutorial >How Can I Properly Access a MySQLi Database Connection from Different PHP Classes?

How Can I Properly Access a MySQLi Database Connection from Different PHP Classes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 02:29:09497browse

How Can I Properly Access a MySQLi Database Connection from Different PHP Classes?

Accessing MySQLi Connection from Other Classes in PHP

When upgrading from PHP 5.6 to 7.0, it is essential to transition from MySQL to MySQLi. This transition can introduce challenges, particularly when attempting to access MySQLi connections from separate classes. This question highlights one such situation where an attempt to connect to a database from an API class using a database class led to an internal server error.

The root of the issue lies in adhering to good programming practices. Extending a user from a database class is incorrect, and the database class itself lacks significant functionality. To resolve this error and improve the overall design, consider the following steps:

  1. Eliminate the redundant Database class. It serves no specific purpose and introduces unnecessary complexity.
  2. Create a single $db instance from vanilla MySQLi. This instance will serve as the central connection point for all database operations.
  3. Pass the $db instance as a constructor parameter to every class that requires a database connection. By following these steps, you establish a cleaner and more maintainable codebase. The updated code structure could resemble:
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 'vendor/autoload.php'; // autoloading is recommended

$api = new MyAPI($db, $request_uri, $postData, $origin);
$user = $api->getUser($_POST['id']);

The above is the detailed content of How Can I Properly Access a MySQLi Database Connection from Different PHP Classes?. 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