Home  >  Article  >  Backend Development  >  How to Share a MySQLi Connection Between Different Classes in PHP?

How to Share a MySQLi Connection Between Different Classes in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 20:32:29500browse

How to Share a MySQLi Connection Between Different Classes in PHP?

Using MySQLi in Classes: A Troubleshooting Guide

Using MySQLi from different classes can be challenging, but don't worry. Let's dive into the issues you've encountered and provide a solution.

Problem: Internal Server Error 500

  • Cause: Attempting to access the conn property of the Database object after creating it in a different class (MyAPI).

Solution: Initialize the Database object within the MyAPI constructor and pass it as a parameter to other functions requiring a database connection. This ensures that all classes sharing the connection have a direct reference to the same instance.

Example:

<code class="php">// myapi.php
class MyAPI {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function getUser($id) {
        $result = mysqli_query($this->db->conn, "SELECT * FROM users WHERE id='$id'");
        return mysqli_fetch_assoc($result);
    }
}

// app.php
// Initialize database once
$db = new mysqli(...);

// Create MyAPI instance with database reference
$api = new MyAPI($db);

// Use MyAPI to access user information
$user = $api->getUser(1);</code>

Additional Considerations:

  • Avoid extending User from Database, as it's not necessary.
  • Directly create a single mysqli instance and pass it to classes that need it.
  • Use prepared statements for better security and performance.
  • Ensure the database connection parameters are correct and the database is accessible.

By following these steps, you should be able to successfully use MySQLi from different classes in PHP.

The above is the detailed content of How to Share a MySQLi Connection Between Different Classes in PHP?. 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