Current Location: Home> Latest Articles> Use the init function to combine mysqli for database connection

Use the init function to combine mysqli for database connection

gitbox 2025-05-29

In PHP, database connections are one of the foundations for developing web applications. We can interact with the database by using MySQLi extensions. To simplify the process of database connection, we usually encapsulate the database connection code into an initialization function. The advantage of this is that we can more easily manage database connections, avoid code redundancy, and improve program maintainability.

This article will explain in detail how to use the init function combined with MySQLi extension to implement database connections and the specific functions of the init function.

1. What is an init function?

The init function is usually an initialization function in the program. In the scenario of database connection, the init function is responsible for setting up and establishing the database connection. Its main function is to create an instance of a database connection, set up relevant configurations, and return a connection object that can perform database operations.

In database operations, the advantages of the init function are:

  • You can centrally manage database connection code to avoid repeated writing in multiple places.

  • The configuration of the database connection can be easily modified when needed without changing the location where each database connection is called.

  • Improve the readability and maintainability of the code.

2. Use MySQLi extension to connect to the database

First, let's see how to use the MySQLi extension to establish a simple database connection.

 <?php
// Database connection configuration
$host = 'localhost';
$user = 'root';
$password = '';
$dbname = 'test_db';

// Create a database connection
$conn = new mysqli($host, $user, $password, $dbname);

// Check if the connection is successful
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connection successfully";
?>

The above code shows a basic MySQLi connection process. First, we create a database connection object $conn through new mysqli() and provide the relevant configuration of the database (database host, username, password and database name). Then, we use the connect_error property to check if the connection is successful, and if the connection fails, an error message is output.

3. How to encapsulate database connections into init functions?

To improve the reusability of the code, we encapsulate the above connection code into a function called init . This not only improves the clarity of the code, but also makes it easier for us to reuse the function in multiple places.

The following is the code that implements the init function:

 <?php
// init Functions are used to initialize database connections
function init() {
    // Database connection configuration
    $host = 'localhost';
    $user = 'root';
    $password = '';
    $dbname = 'test_db';
    
    // Create a database connection
    $conn = new mysqli($host, $user, $password, $dbname);
    
    // Check if the connection is successful
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    return $conn;  // Return the database connection object
}

// Call init Function to get database connection
$conn = init();

// Now available $conn Objects perform database operations
echo "Connection successfully";
?>

In the above code, the init function encapsulates all database connection logic. When we call the init() function, it returns a database connection object $conn , through which we can perform database query or other operations.

4. Use encapsulated init function for database query

Once we get the database connection object through the init function, we can start executing the database query operation. Here is a simple example showing how to query data in a database using encapsulated init functions:

 <?php
// Call init Function to get database connection
$conn = init();

// Perform query operations
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

// Check whether the query is successful
if ($result->num_rows > 0) {
    // Output query results
    while ($row = $result->fetch_assoc()) {
        echo "username: " . $row["username"] . "<br>";
        echo "Mail: " . $row["email"] . "<br>";
    }
} else {
    echo "No record found";
}

// Close the database connection
$conn->close();
?>

In this example, we first call the init function to get the database connection, and then execute a SELECT query to query all records in the users table. Execute the query through the query() method and use the fetch_assoc() method to output the query results line by line.

5. Summary

By encapsulating database connections into init functions, we effectively simplify the management and use of code. In actual development, the init function is usually placed in a special database class or configuration file to further enhance the structure and maintainability of the program. In this way, the creation and use of database connections becomes more flexible and manageable.

Hope this article helps you understand how to implement database connections through init functions combined with MySQLi extensions and the role of init functions in it. If you have other questions about PHP or database, feel free to ask questions!