Current Location: Home> Latest Articles> Use the init function to cooperate with PDO to implement database initialization

Use the init function to cooperate with PDO to implement database initialization

gitbox 2025-05-28

In PHP development, database connections are a very important part, especially when sharing database connection configurations between multiple pages and modules, it is particularly important to manage database connections gracefully. By using init functions and PDO (PHP Data Objects) to initialize and manage connection configurations, it not only ensures code reusability, but also effectively avoids repeated connection creation and improves application performance.

1. Introduction

In multi-module applications, repetitive creation of database connections not only wastes resources, but also increases the complexity of maintenance. Using PDO as a database access method can facilitate management of database connections and provide a unified interface for database operations. With the init function, database initialization and connection configuration can be more clear and centrally managed.

2. Preparation

First, we need to enable PDO extensions in our PHP environment and ensure that we have permission to access the database. Here is the basic configuration using PDO :

 <?php
$dsn = 'mysql:host=gitbox.net;dbname=my_database';
$username = 'db_user';
$password = 'db_password';

try {
    $pdo = new PDO($dsn, $username, $password);
    // Set the error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Database connection is successful!";
} catch (PDOException $e) {
    echo "Database connection failed: " . $e->getMessage();
}
?>

The above code creates a basic database connection. At this point, we encapsulate this process into an init function, which facilitates call and manage database connections when needed.

3. Use the init function to encapsulate the database connection

Next, we encapsulate the logic of the database connection in an init function. In this way, the initialization of database connections can be centrally managed, avoiding duplicate code, and facilitates later maintenance and modification.

 <?php
class Database {
    private static $pdo = null;

    // Database initialization function
    public static function init() {
        if (self::$pdo === null) {
            $dsn = 'mysql:host=gitbox.net;dbname=my_database';
            $username = 'db_user';
            $password = 'db_password';
            try {
                self::$pdo = new PDO($dsn, $username, $password);
                self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {
                die("Database connection failed: " . $e->getMessage());
            }
        }
        return self::$pdo;
    }

    // Close the database connection
    public static function close() {
        self::$pdo = null;
    }
}
?>

4. How to use this init function

Once we initialize the database connection through the init function, we can reuse this connection throughout the application. Here is an example of how to use this function:

 <?php
// Call init Function initialize database connection
$db = Database::init();

// Perform database query
$query = $db->query('SELECT * FROM users');
$results = $query->fetchAll(PDO::FETCH_ASSOC);

foreach ($results as $row) {
    echo 'username: ' . $row['username'] . '<br>';
}

// Close the connection
Database::close();
?>

In the example above, we first call Database::init() to get the database connection. Then, the database query operation is performed through the $db object, and finally, after the operation is completed , Database::close() is called to close the connection.

5. Why use the init function to manage database connections?

  • Avoid duplicate connections : If a new database connection is created in different pages or classes, it will result in performance waste. Through the init function, we will only create a database connection when we need it the first time, and subsequent operations will reuse this connection.

  • Centralized management configuration : The configuration of database connections is concentrated in one place, which is very convenient to modify. If the database address, username or password changes, it only needs to be modified once in the init function, and no changes are required elsewhere.

  • Error handling and exception management : By encapsulating database connections in the init function, we can handle exceptions and errors centrally in one place, which makes error tracking and debugging more convenient.

6. Summary

Through the init function combined with PDO, we can efficiently manage database connections, avoiding the overhead of repeatedly creating connections, while keeping the code clear and maintainable. This database management method is very suitable for both small applications and large systems. Encapsulating the initialization process of database connections into functions is a good programming practice that can make your code more readable and maintainable.