Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check Whether mysqli connection is open before closing it

Tags:

php

mysqli

I am going to use mysqli_close($connection) to close the $connection. But Before Closing I need to ensure that the concerned connection is open.

I tried

if($connection) {   mysqli_close($connection); } 

But it is not working. Any Solution?

like image 465
Munib Avatar asked May 01 '13 13:05

Munib


People also ask

Do I need to close MySQLi connection?

Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.

How do I know if MySQLi is working?

Check if MySQLi is Installed The first step is to check if MySQLi extension is installed. You can do that by visiting a phpinfo() page that you made, or by running this command: php -m | grep mysqli.

What happens if you don't close MySQL connection?

"Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."


1 Answers

This is from PHP.net.

Object oriented style


<?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world");  /* check connection */ if ($mysqli->connect_errno) {     printf("Connect failed: %s\n", $mysqli->connect_error);     exit(); }  /* check if server is alive */ if ($mysqli->ping()) {     printf ("Our connection is ok!\n"); } else {     printf ("Error: %s\n", $mysqli->error); }  /* close connection */ $mysqli->close(); ?> 

Procedural style


<?php $link = mysqli_connect("localhost", "my_user", "my_password", "world");  /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); }  /* check if server is alive */ if (mysqli_ping($link)) {     printf ("Our connection is ok!\n"); } else {     printf ("Error: %s\n", mysqli_error($link)); }  /* close connection */ mysqli_close($link); ?> 
like image 128
user2060451 Avatar answered Oct 13 '22 08:10

user2060451