How to Check Whether mysqli connection is open before closing it

Munib picture Munib · May 1, 2013 · Viewed 58.4k times · Source

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?

Answer

user2060451 picture user2060451 · Oct 4, 2013

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);
?>