"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Share a MySQLi Connection Between Different Classes in PHP?

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

Published on 2024-11-02
Browse:477

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:

// 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);

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3