Home >Database >Mysql Tutorial >How to Properly Use MySQLi Connections Across Different PHP Classes?

How to Properly Use MySQLi Connections Across Different PHP Classes?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 06:26:10640browse

How to Properly Use MySQLi Connections Across Different PHP Classes?

Using MySQLi from Another Class in PHP

When upgrading from PHP 5.6 to 7.0, it is necessary to update from MySQL to MySQLi. However, this can sometimes lead to setup issues.

Problem:

After upgrading to PHP 7.0 and MySQLi, attempting to access database connections using $this->db->conn results in an internal server error 500, even though creating the database connection directly in the class works.

Solution:

The error is caused by several bad practices:

  • Extending a class from Database is incorrect.
  • The Database class itself is not useful as it does not provide any functionality.

To resolve the issue:

  1. Eliminate the Database class.
  2. Create a single $db instance from plain mysqli.
  3. Pass this instance as a constructor parameter to any class that requires a database connection.

Example Code:

// database.php
$db = new mysqli("localhost", "DBUserName", "UserPassword", "SelectedDB");
$db->set_charset('utf8mb4');
// myapi.php
class MyAPI
{
    protected $db;

    public function __construct($db, $request_uri, $postData, $origin)
    {
        $this->db = $db;
    }
    // ... (rest of the class omitted for brevity)
}
// app.php
require 'vendor/autoload.php'; // assuming autoloading is set up

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

By following these guidelines, you can successfully use MySQLi from other classes in PHP.

The above is the detailed content of How to Properly Use MySQLi Connections Across 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