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

Susan Sarandon
Release: 2024-10-25 20:32:29
Original
413 people have browsed it

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

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!

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!