Welcome to this comprehensive guide on PHP MySQLi Close Connection! By the end of this tutorial, you'll understand the importance of closing database connections and learn how to do it effectively in PHP. Let's get started! π
When you establish a connection between your PHP script and the MySQL database, resources are allocated for this connection. To ensure optimal performance and prevent memory leaks, it's essential to release these resources when they're no longer needed. Closing the database connection is the way to achieve this.
First, let's create a simple PHP script that connects to a MySQL database:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}Now that we have a working connection, let's see how to close it.
To close the database connection, you can use the close() method on the connection object:
// Close connection
$conn->close();Add the above line at the end of your PHP script, right before the closing PHP tag (?>).
Let's modify our previous example to include a query, fetch results, and close the connection:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create and execute a query
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);
// Fetch results
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();This script connects to a MySQL database, executes a query, fetches results, and closes the connection when it's done.
Why is it important to close database connections in PHP?
That's it for this tutorial on PHP MySQLi Close Connection! As you practice writing PHP scripts, remember to always close your database connections to ensure optimal performance. Keep learning, keep coding! π‘π―