YouTip LogoYouTip

Func Mysqli Close

```html PHP mysqli_close() Function

PHP mysqli_close() Function

PHP mysqli_close() Function

Complete MySQLi Function Reference

For a complete reference of all MySQLi functions, go to our complete PHP MySQLi Reference.

Definition and Usage

The mysqli_close() function closes a previously opened database connection.

Syntax

mysqli_close(connection);

Parameter Values

Parameter Description
connection Required. Specifies the MySQL connection to close

Technical Details

Return Value: TRUE on success, FALSE on failure
PHP Version: 5+
Changelog: Function/method deprecated in PHP 5.5.0, and removed in PHP 7.0.0
Note: There is no need to close the connection manually as PHP automatically closes the connection when the script ends. However, it is recommended to close the connection explicitly when it's no longer needed to free up server resources.

Example

Close a database connection:

<?php
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
}

// Perform some operations here...

// Close connection
mysqli_close($conn);
?>

More Examples

Example 1: Complete Database Connection Example

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";

// Close connection
mysqli_close($conn);
?>

Example 2: Using Object-Oriented Style

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";

$conn->close();
?>

Example 3: Why Close the Connection?

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection without selecting a database
$conn = mysqli_connect($servername, $username, $password);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

// It's good practice to close the connection when done
// This frees up server resources for other operations
mysqli_close($conn);
?>

Best Practices

1. Always Check Connection First

<?php
$conn = mysqli_connect("localhost", "user", "pass", "database");

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Use the connection...

// Always close the connection
mysqli_close($conn);
?>

2. Use try-catch for Error Handling

<?php
function connectToDatabase() {
    $conn = mysqli_connect("localhost", "user", "pass", "database");
    
    if (!$conn) {
        throw new Exception("Database connection failed: " . mysqli_connect_error());
    }
    
    return $conn;
}

try {
    $conn = connectToDatabase();
    
    // Database operations...
    
    mysqli_close($conn);
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

3. Connection Pooling Considerations

In high-traffic applications, consider using persistent connections or connection pooling to improve performance:

<?php
// Using persistent connection
$conn = mysqli_connect("p:localhost", "user", "pass", "database");

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Your code here...

mysqli_close($conn);
?>

Common Errors and Solutions

Error 1: Trying to Close a Non-existent Connection

// Wrong
$conn = mysqli_connect("localhost", "user", "pass");
$conn2 = mysqli_connect("localhost", "user", "pass");

mysqli_close($conn); // This is correct
// $conn2 is still open and will be closed automatically at script end

Error 2: Using Closed Connection

// Wrong - will cause errors
$conn = mysqli_connect("localhost", "user", "pass", "database");
mysqli_close($conn);
$result = mysqli_query($conn, "SELECT * FROM users"); // Error!

// Correct - check if connection is still open
$conn = mysqli_connect("localhost", "user", "pass", "database");
mysqli_close($conn);
if (mysqli_ping($conn)) {
    // Connection is still active
    $result = mysqli_query($conn, "SELECT * FROM users");
} else {
    echo "Connection is closed";
}

Error 3: Not Closing Connection in Long-running Scripts

// For long-running scripts, always close and reopen connections
$conn = mysqli_connect("localhost", "user", "pass", "database");

// First batch of operations
processFirstBatch($conn);

// Close to free resources
mysqli_close($conn);

// Take a break...
sleep(30);

// Reopen connection for next batch
$conn = mysqli_connect("localhost", "user", "pass", "database");
processSecondBatch($conn);

// Final close
mysqli_close($conn);
?>

Performance Considerations

When to Close Connections Explicitly

  • Long-running scripts: Close connections between operations to free up server resources.
  • High-traffic applications: Explicit closing prevents connection pool exhaustion.
  • Script termination: Though PHP closes connections automatically, explicit closing is better practice.

Connection Timeout Settings

<?php
$conn = mysqli_connect("localhost", "user", "pass", "database");

// Set connection timeout
mysqli_options($conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5);

// Set read timeout
mysqli_options($conn, MYSQLI_OPT_READ_TIMEOUT, 30);

// Set write timeout
mysqli_options($conn, MYSQLI_OPT_WRITE_TIMEOUT, 30);

// Remember to close
mysqli_close($conn);
?>

Conclusion

The mysqli_close() function is an essential part of database connection management in PHP. While PHP automatically closes connections at the end of script execution, explicitly closing connections is a best practice that:

  • Frees up server resources immediately
  • Prevents connection pool exhaustion in high-traffic scenarios
  • Makes your code more predictable and maintainable
  • Improves overall application performance

Always remember to close your database connections when they're no longer needed!

Comments

© 2024 . All rights reserved.

Learning not just technology, but also dreams!

```
← Func Mysqli CommitFunc Mysqli Character Set Name β†’